简体   繁体   中英

java Get value from xml tag

I have an XML file:

<Header>
 <Id>A203</Id>
 <Name>ABC</Name>
</Header>

I'm trying to check whether the XML file's Id value is "A203" or not. I tried the following way but still can't get the value. I can't use xPath because I have an older Java version.

DocumentBuilderFactory dbfaFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbfaFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlfile);

doc.getElementsByTagName("Id").item(0).getNodeValue());   --tried this but cant

Getting the node value of an element will return null (as documented here ).

Instead you need to either get the element's text content (since Java 5):

doc.getElementsByTagName("Id").item(0).getTextContent();

Or, if you're stuck in Java 1.4 or older, you can access the element's text node and get the text node's value:

doc.getElementsByTagName("Id").item(0).getFirstChild().getNodeValue();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM