我想操縱xsd模式作爲一個xml文檔,我認爲這不應該是一個問題。但面臨XPath的麻煩。無論我嘗試XPath,它都不會返回任何內容。嘗試使用或不使用命名空間,但沒有成功。 請幫我理解我做錯了什麼?我在做什麼錯誤的XPath?
我的XML是:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.mydomain.com" xmlns="http://www.mydomain.com" elementFormDefault="qualified">
<xs:complexType name="Label">
<xs:choice maxOccurs="unbounded" minOccurs="0">
<xs:element name="Listener"/>
</xs:choice>
</xs:complexType>
</xs:schema>
和應用程序代碼是:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setValidating(false);
domFactory.setNamespaceAware(true);
domFactory.setIgnoringComments(true);
domFactory.setIgnoringElementContentWhitespace(true);
try {
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document dDoc = builder.parse("C:/Temp/test.xsd");
// This part works
Node rootNode = dDoc.getElementsByTagName("xs:schema").item(0);
System.out.println(rootNode.getNodeName());
// This part doesn't work
XPath xPath1 = XPathFactory.newInstance().newXPath();
NodeList nList1 = (NodeList) xPath1.evaluate("//xs:schema", dDoc, XPathConstants.NODESET);
System.out.println(nList1.item(0).getNodeName());
// This part doesn't work
XPath xPath2 = XPathFactory.newInstance().newXPath();
NodeList nList2 = (NodeList) xPath2.evaluate("//xs:element", rootNode, XPathConstants.NODESET);
System.out.println(nList2.item(0).getNodeName());
}catch (Exception e){
e.printStackTrace();
}
然後xPath1.evaluate(「// schema」,...)應該這樣做嗎? – willcodejavaforfood 2010-08-25 17:58:04
@willcodejavaforfood:No.'// schema'表示沒有命名空間下樹中的任何'schema'元素。應該是'/ xs:schema' – 2010-08-25 18:14:18
@Ajjandro - 確定這很有意義,謝謝 – willcodejavaforfood 2010-08-25 20:40:16