我有一個如下的xml:
<root>
<outer>
<name>abc</name>
<age>20</age>
</outer>
<outer>
<name>def</name>
<age>30</age>
</outer>
<outer>
<name>ghi</name>
<age>40</age>
</outer>
</root>
我想獲取給定名稱標簽值的年齡標簽值?
一種方法是我可以通過使用 Document 介面決議這個 xml 來準備一張姓名到年齡的地圖。
但是有沒有我可以呼叫 Document 介面的 api,在其中我可以說 fetch 名稱為 say,ghi 的元素,然后我可以迭代所有屬性以獲取年齡屬性或任何其他簡單的方法來獲取名稱值的年齡,說吉?
uj5u.com熱心網友回復:
原來 java 確實在package中附帶了一個XPath評估器,這使得這變得微不足道:javax.xml.xpath
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
public class Demo {
public static void main(String[] args) throws Exception {
String name = "ghi";
// XPath expression to find an outer tag with a given name tag
// and return its age tag
String expression = String.format("/root/outer[name='%s']/age", name);
// Parse an XML document
DocumentBuilder builder
= DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(new File("example.xml"));
// Get an XPath object and evaluate the expression
XPath xpath = XPathFactory.newInstance().newXPath();
int age = xpath.evaluateExpression(expression, document, Integer.class);
System.out.println(name " is " age " years old");
}
}
示例使用:
$ java Demo.java
ghi is 40 years old
uj5u.com熱心網友回復:
XPath 是一個非常有表現力的 API,可用于選擇元素。
/root/outer[name = "ghi"]/age
這篇文章https://www.baeldung.com/java-xpath很好地概述和解釋了如何在 Java 中應用 XPath。
為您的 XPath 調整他們的代碼示例之一:
String name = "ghe";
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/root/outer[name=" "'" name "'" "]/age";
node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/430483.html
上一篇:如何將awsapi網關連接到vpc內的私有lambda函式
下一篇:將注釋檔案添加到XSD子元素
