【发布时间】:2014-03-13 08:05:28
【问题描述】:
嘿,我是使用 Java 读取 XML 文件的新手,我的问题是我一直在尝试读取 xml,并且在特定标签之间我想获取所需的数据,我正在使用 XPath,我的查询是:
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[@type='STRING']";
它工作正常,我要读取的特定标签是:
<ATTRIBUTE name="Description" type="STRING"> SOME TEXT </ATTRIBUTE>
但我只想读取这些类型的标签中的数据,因此我的输出应该是:
SOME TEXT
在标签里面! 有人可以帮助我我该怎么做请我是 xml 阅读的新手!尽我所能:
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[@name='Description' and ./type/text()='STRING']";
但它不会给我任何输出! 提前谢谢
我的代码:
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(
new FileInputStream("c:\\y.xml"));
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[@name='Description'and @type='STRING']";
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.print(e);
}
我的代码有问题,无法弄清楚是什么!
【问题讨论】: