read single node xml in java
I am doing request to remote server and get this xml response with single string tag.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1405</string>
How can I get value(1405) of string tag?
I tried this, but it does not work开发者_运维知识库:
NodeList nl = doc.getElementsByTagName("string");
Node n = nl.item(0);
String root = n.getNodeValue();
There are options other than using DOM:
XPath - javax.xml.path (Available as part of Java SE 5)
An example:
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class Demo {
public static void main(String[] args) throws Exception {
String xml = "<car><manufacturer>toyota</manufacturer></car>";
String xpath = "/car/manufacturer";
XPath xPath = XPathFactory.newInstance().newXPath();
assertEquals("toyota",xPath.evaluate(xpath, new InputSource(new StringReader(xml))));
}
}
JAXB - javax.xml.bind (Available as part of Java SE 6)
Domain Object
package com.example;
import javax.xml.bind.annotations.*;
@XmlRootElement(name="string", namespace="http://schemas.microsoft.com/2003/10/Serialization/")
public class StringValue {
private String value;
@XmlValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Demo
package com.example;
public class Demo {
public static void main(String[] args) {
JAXBContext jc = JAXBContext.newInstance(StringValue.class);
Unmarshaller u = jc.createUnmarshaller();
StringValue stringValue = (StringValue) u.unmarshal(xml);
System.out.println(stringValue.getValue());
}
}
You don't have to specify XML namespace in your Java code. The reason why you get null instead of "1045" is that because n.getNodeValue() actually returns value of element node (org.w3c.dom.Element), not inner text node (org.w3c.dom.Text).
String root = n.getTextContent();
String root = n.getFirstChild().getNodeValue(); // in some environments safer way
That is because the text “1405” is not the value of the <string> tag’s element. It is instead the value of a text node that is a direct child of the <string> tag’s element. See the table here.
精彩评论