使用XPath Java在Tag内部读取
Hye我是新手阅读使用Java的XML文件我的问题是我一直在尝试读取xml和特定标签之间我想获取所需的数据我使用的是XPath,我的查询是:
String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[@type='STRING']";
它工作正常,我的特定标签是:
SOME TEXT
但我想只读取这些类型的标签内的数据,以便我的输出应该是:
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); }
我的代码有问题无法弄清楚是什么!
使用已更改的XPath,此代码适用于我:
"/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[@name='Description'][@type='STRING']"
:
private static final String EXAMPLE_XML = "" + "" + "" + "" + "" + " " + "kvarga " + "I WANT THIS PARA 2 " + " " + " " + " " + " "; public static void main(String[] args) { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(new ByteArrayInputStream(EXAMPLE_XML.getBytes())); XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/ADOXML/MODELS/MODEL/MODELATTRIBUTES/ATTRIBUTE[@name='Description'][@type='STRING']"; 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 (Exception e) { System.out.print(e); } }
OUTPUT:
###I WANT THIS PARA 2###
提到的代码工作正常。
您也可以尝试其他方式来获取文本节点 –
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());