javaxmlparsingelementname

XML Parsing with Java: <element name ="doctype">


Possible Duplicate:
how to retrieve element value of XML using Java?

I am trying to parse a xml file with java using dom. The xml looks like this:

<documents>
  <document>
    <element name="doctype">
      <value>Circular</value>
    </element>
  </document>
</documents>

Geting the root node "documents" and also the child node "document" is easy. But I can't get the value of the element with the name "doctype" (I want to store the value "Circular" in a database). Can someone help me please?


Solution

  • You could use the following XPath to get the data you are looking for:

    /documents/document/element[@name='doctype']/value
    

    Demo

    The following demo code demonstrates how to execute that XPath against your DOM. This application will run in any standard Java SE 5 (or newer) install.

    package forum11578831;
    
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    import org.w3c.dom.Document;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse("src/forum11578831/input.xml");
    
            XPath xPath = XPathFactory.newInstance().newXPath();
            String string = (String) xPath.evaluate("/documents/document/element[@name='doctype']/value", dDoc, XPathConstants.STRING);
            System.out.println(string);
        }
    
    }
    

    input.xml

    I have expanded the XML document to contain element elements with name attributes with values other that doctype to demonstrate that the XPath works.

    <documents>
      <document>
        <element name="foo">
          <value>FOO</value>
        </element>
        <element name="doctype">
          <value>Circular</value>
        </element>
        <element name="bar">
          <value>BAR</value>
        </element>
      </document>
    </documents>
    

    Output

    The result of executing the XPath is the very String you are looking for:

    Circular