这是我的XML(wls.xml)
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
这是XSD(wls.xsd)
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
这是我用来使用Xpath解析上述文件的java类
public static void test1()
{
String ipFile="w3s.xml";//wls.xsd
Node fetchNode=null;
FileInputStream fileip;
try {
fileip = new FileInputStream(new File(ipFile));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document xmlDocument = builder.parse(fileip);
System.out.println(xmlDocument.getDocumentElement().getNodeName());
System.out.println(xmlDocument.getDocumentElement().getLocalName());
evalXpath(xmlDocument,"//xs:element");//FAILS
evalXpath(xmlDocument,"//element");//FAILS
evalXpath(xmlDocument,"/schema/element");//WORKS
evalXpath(xmlDocument,"/xs:schema/xs:element");//FAILS
evalXpath(xmlDocument,"//heading");//FAILS
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void evalXpath(Document xmlDocument,String expression)
{
Node fetchNode=null;
NodeList fetchNodeList=null;
//String expression=null;
try
{
XPath xPath = XPathFactory.newInstance().newXPath();
fetchNode = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
System.out.println(fetchNode);
fetchNodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
System.out.println(fetchNodeList.getLength());
}
catch (XPathExpressionException e) {
e.printStackTrace();
}
}
}
当我解析XML文件并运行类型'\ ElemName'的表达式时,它可以正常工作并获取节点。然后我不会对XSD文件做同样的事情,它返回NULL。 对于XSD,我需要起诉'\ RootNode \ IntermediateNode .... \ ReqdNode' 我尝试使用名称不同的XML和XSD,只是附加这些短文件用于说明目的。
Issue2 还有一个问题: 如果我有一个元素'xs:schema',我只需要获得像'schema'这样的本地名称部分(没有名称空间前缀),我该怎么办呢?我尝试了getLocalName()但它不起作用。
(如果你需要知道,我正在使用jdk6)
请至少在我的第一期内提供解决方案。
提前致谢。
答案 0 :(得分:0)
如果您尝试让XPath处理XSD架构,请确保从XSD xmlns:xs="http://www.w3.org/2001/XMLSchema"
声明命名空间。
如果您不想使用命名空间,可以按如下方式使用XPath:
//*[local-name()='element']
/*[local-name()='schema']/*[local-name()='element']