我刚开始使用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);
} 我的代码出了问题,搞不清楚是什么!
发布于 2014-03-13 08:38:19
上述代码工作正常。
你也可以尝试其他方法来获取文本节点-
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE/text()";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
System.out.println(nodeList.item(0).getNodeValue());https://stackoverflow.com/questions/22372533
复制相似问题