如果父节点下存在两个节点,我如何获取节点的值。例如:我有以下 Xml。
<?xml version="1.0" encoding="UTF-8"?>
<Services xmlns="http://sample.schema.com/abc">
<service>
<name>Sample</name>
<uri>/v9.0/sample.123.com
</uri>
</service>
<service>
<name>Sample 2</name>
</service>
<service>
<name>Sample 3</name>
<uri>/v9.0/sample3.123.com
</uri>
</service>
<service>
<name>Sample 4</name>
<uri>/v9.0/sample4.123.com
</uri>
</service>
<service>
<name>Sample 5</name>
<uri>/v9.0/sample5.123.com
</uri>
</service>
<service>
<name>Sample 6</name>
</service>
<service>
<name>Sample 7</name>
<uri>/v9.0/sample7.123.com
</uri>
</service>
<service>
<name>Sample 8</name>
</service>
</Services>
我的代码:
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class SimpleXpath {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(false); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("testService1.xml");
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//Services/service[(name) and (uri)/text()]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
String value=nodes.item(i).getNodeValue();
System.out.println(" output : "+i+" "+value);
}
}
}
我想从上面的 xml 中读取 name 和 url 的值,如果 name 和 uri 存在于服务节点下。我们可以看到,有些服务节点只包含名称。我想避免那些。我的 xpath 表达式将 null 值作为输出。
如果服务包含两者,我如何获取名称和 uri 的“文本”?
我可以使用 xpath 将输出作为名称作为第一个,将 uri 作为第二个(如果两者都在服务中)?
非常感谢。
约翰