XSD 架构:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://www.xxx.sk/sirs"
elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:sir="http://www.xxx.sk/sirs">
<xsd:complexType name="Detail_begin">
<xsd:sequence>
<xsd:element name="Block" type="xsd:int"></xsd:element>
<xsd:element name="Select" type="xsd:string"></xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="MASK">
<xsd:sequence>
<xsd:element name="Number_of_client" type="xsd:int"></xsd:element>
<xsd:element name="Indicator" type="xsd:string"></xsd:element>
<xsd:element name="Domicile" type="xsd:string"></xsd:element>
<xsd:element name="City" type="xsd:string"></xsd:element>
<xsd:element name="Sector" type="xsd:string"</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
我需要使用 name="Detail_begin" 和 name="MASK" 读取所有元素的 complexType。在 XSD 中有更复杂的类型。哪种方式更容易?Xpath OR Node 还是别的什么?我试过这样:
public class XsdRead {
public static void main(String[] args) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
Document xmlDocument = null;
try {
DocumentBuilder builder = builderFactory.newDocumentBuilder();
xmlDocument = builder.parse(new FileInputStream("xml/XmlSchema2.xsd"));
} catch (Exception e) {
e.printStackTrace();
}
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//xsd:complexType[@name='Detail_begin' or @name='MASK']//xsd:element";
NodeList result = null;
try {
result = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
for (int i = 0; i < result.getLength(); i++) {
Element el = (Element)result.item(i);
System.out.println(el.getAttribute("name") + " = " + el.getNodeValue());
}
}
}
谢谢你的建议。