xml-xalan-j-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Chad Berkley <berk...@nceas.ucsb.edu>
Subject Re: XPath to generate XML
Date Tue, 01 Oct 2002 14:48:19 GMT
Here is some simple java code that I wrote to do something similar to
what you are talking about, though it does not even attempt to implement
full xpath...but it probably could.

/**
   * builds a document from a path.  the document is returned empty.
   * if you pass this /x/y/z you will get back a document of the form
   * &lt;x&gt;&lt;y&gt;&lt;z&gt;&lt;/z&gt;&lt;/y&gt;&lt;/x&gt;
   * @param path the path to parse
   */
  private Document buildDocumentFromPath(String path)
  {
    try
    {
      DocumentBuilder builder =  
        DocumentBuilderFactory.newInstance().newDocumentBuilder();
      StringBuffer xml = new StringBuffer();
      Stack s = new Stack();

      StringTokenizer tokenizer = new StringTokenizer(path, "/");
      while(tokenizer.hasMoreElements())
      {
        String node = tokenizer.nextToken();
        xml.append("<").append(node).append(">");
        s.push(node);
      }

      while(!s.empty())
      {
        String node = (String)s.pop();
        xml.append("</").append(node).append(">");
      }

      return builder.parse(new InputSource(new     
                           StringReader(xml.toString())));
    }
    catch(Exception e)
    {
      throw new EMLParserException("Error building document " +       
                                   "fragment:" + e.getMessage());
    }
  }

hope it's useful.

chad

-- 
-----------------------
Chad Berkley
National Center for 
Ecological Analysis 
and Synthesis (NCEAS)
berkley@nceas.ucsb.edu
-----------------------

On Mon, 2002-09-30 at 18:01, Shekhar Jha wrote:
> I am thinking along the lines of generating a skeleton DOM
> using the path i.e. along the line of 
> instead of writing a code like
> ...
> Element element = document.createElement("Order"));
> document.appendChild(element);
> Node node = XPathAPI.selectSingleNode("/Order");
> node.appendChild( document.createElement("Customer" ) );
> Node node = XPathAPI.selectSingleNode("/Order/Customer[1]");
> node.appendChild( document.createElement("Name" ) );
> Node node = XPathAPI.selectSingleNode("/Order/Customer[1]/Name");
> node.appendChild(document.createText("John Doe") );
> ....
> 
> I would like to just do
> ... 
> Node node = XPathAPI.selectSingleNode("/Order/Customer[1]/Name");
> node.appendChild(document.createText("John Doe") );
> ....
> 
> Does this make sense? I am banking on the fact that XPath implementation would
> have a tree of some sort that I can traverse to generate the DOM.
> I am not a XML expert and am NOT sure whether what I am looking for is valid
> in XML world!!
> Thanks for all your help
> Shekhar Jha



Mime
View raw message