gpt4 book ai didi

java - 使用 XPATH 在 Java 中解析 XML 节点

转载 作者:行者123 更新时间:2023-11-30 04:57:31 30 4
gpt4 key购买 nike

我刚刚开始尝试 Jaxp13XPathTemplate,但我对解析 XML 有点困惑。

这是示例 XML

<fxDataSets> 
<fxDataSet name="NAME_A">
<link rel="self" href="http://localhost:8080/linkA"/>
<baseCurrency>EUR</baseCurrency>
<description>TEST DESCRIPTION A</description>
</fxDataSet>

<fxDataSet name="NAME_B">
<link rel="self" href="http://localhost:8080/linkB"/>
<baseCurrency>EUR</baseCurrency>
<description>TEST DESCRIPTION B</description>
</fxDataSet>
<fxDataSets>

我已经能够获取 NAME_A 和 NAME_B,但是我无法获取这两个节点的描述。

这是我的想法。

XPathOperations  xpathTemplate = new Jaxp13XPathTemplate();
String fxRateURL = "http://localhost:8080/rate/datasets";
RestTemplate restTemplate = new RestTemplate();
Source fxRate = restTemplate.getForObject(fxRateURL,Source.class);
List<Map<String, Object>> currencyList = xpathTemplate.evaluate("//fxDataSet", fxRate , new NodeMapper() {
public Object mapNode(Node node, int i) throws DOMException
{
Map<String, Object> singleFXMap = new HashMap<String, Object>();
Element fxDataSet = (Element) node;
String id = fxDataSet.getAttribute("name");

/* This part is not working
if(fxDataSet.hasChildNodes())
{
NodeList nodeList = fxDataSet.getChildNodes();
int length = nodeList.getLength();

for(int index=0;i<length;i++)
{
Node childNode = nodeList.item(index);
System.out.println("childNode name"+childNode.getLocalName()+":"+childNode.getNodeValue());
}

}*/

return new Object();
}
});

最佳答案

尝试使用 dom4j 库,它是 saxReader。

    InputStream is = FileUtils.class.getResourceAsStream("file.xml");

SAXReader reader = new SAXReader();
org.dom4j.Document doc = reader.read(is);
is.close();
Element content = doc.getRootElement(); //this will return the root element in your xml file
List<Element> methodEls = content.elements("element"); // this will retun List of all Elements with name "element"

关于java - 使用 XPATH 在 Java 中解析 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8061004/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com