使用java从xml中标记值

使用java从xml中标记值,java,xml,xml-parsing,Java,Xml,Xml Parsing,在下面的示例中,假设file.xml 标签return code=中有值,我只需要里面的值 我需要得到的价值 哪个在里面 里面 . 在本例中,我需要得到值1和0。如果您在使用xpath时没有任何问题,那么您可以尝试以下方法: 必须在参数中给出xml文件的路径 XPathReader reader = new XPathReader("FileName.xml"); // To get a xml attribute. String expression = "/Main/Po

在下面的示例中,假设file.xml 标签return code=中有值,我只需要里面的值

我需要得到的价值 哪个在里面 里面 .
在本例中,我需要得到值1和0。

如果您在使用xpath时没有任何问题,那么您可以尝试以下方法:

必须在参数中给出xml文件的路径

   XPathReader reader = new XPathReader("FileName.xml");

   // To get a xml attribute.
   String expression = "/Main/Port/output/@code";

   System.out.println(reader.read(expression,XPathConstants.STRING) + "n");

如果XML是字符串,则可以执行以下操作:

String xml = ""; //Populated XML String....
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = DocumentBuilderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();
如果XML位于文件中,则文档将按如下方式实例化:

Document document = builder.parse(new File("file.xml"));
for (int i = 0; i < nl.getLength(); i++) {
    Node node = nl.item(i);
    System.out.println(node.getNodeValue());
}
getDocumentElement返回您案例中文档的文档元素节点

一旦有了rootElement,就可以通过调用rootElement.getAttribute方法等来访问该元素的属性,以获取java的org.w3c.dom.element上的更多方法

为了进一步澄清,请查看此链接,它对您有很大帮助


干杯

XPath可能是解决这个问题的方法

我已经将xml文件作为一种资源,但是您可以将它放在一个文件结构中

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
ClassLoader loader = XmlTestReader.class.getClassLoader();
InputStream is = loader.getResourceAsStream("test.xml");
Document doc = builder.parse(is);
然后创建一个XPath表达式

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression expr = xPath.compile("/Main/Port[@name='write_qwe']/output/return/@code");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
XPath表达式/Main/Port[@name='write_qwe']/output/return/@code将查找端口属性名为write_qwe的所有代码属性

现在您可以像这样迭代节点:

Document document = builder.parse(new File("file.xml"));
for (int i = 0; i < nl.getLength(); i++) {
    Node node = nl.item(i);
    System.out.println(node.getNodeValue());
}
编辑

根据的建议,最好使用InputSource作为XPathExpressionevaluate的输入:


我建议使用DOM,XPath,试试这个,它会帮助你@paul我已经完成了代码,直到它检查read\u abc还是write_qwe@Sath:是的,我检查了,但它没有给出标记返回码=中的值,执行检查有什么困难?+1-但我建议调用接受InputSource的evaluate方法。如果XPath实现不需要DOM,那么它就有机会不构建DOM。这会导致性能的提高。@BlaiseDoughan我在答案中添加了您的建议。谢谢
ClassLoader loader = XmlTestReader.class.getClassLoader();
InputStream inputStream = loader.getResourceAsStream("test.xml");
InputSource inputSource = new InputSource(inputStream);

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression expr = xPath.compile("/Main/Port[@name='write_qwe']/output/return/@code");
NodeList nl = (NodeList) expr.evaluate(inputSource , XPathConstants.NODESET);