gpt4 book ai didi

Java解析XML以获取子元素值

转载 作者:行者123 更新时间:2023-11-30 07:44:05 25 4
gpt4 key购买 nike

我有一个包含以下 XML 代码的 java 字符串:

<?xml version="1.0" encoding="utf-8"?>
<Chart>
<request>
<zip>12345</zip>
<city>Miami</city>
</request>
</Chart>

解析该字符串以提取值的最简单方法是什么

<zip> (in this case 12345)

最佳答案

你有 XML,最好将其解析为 XML,然后直接使用 XPATH

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;


String xml="<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
" <Chart>\r\n" +
" <request>\r\n" +
" <zip>12345</zip>\r\n" +
" <city>Miami</city>\r\n" +
" </request>\r\n" +
" </Chart>";

DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();

// PARSE XML
Document document = builder.parse(new InputSource(new StringReader(xml)));

// XPATH
XPath xPath = XPathFactory.newInstance().newXPath();
// your path
String expression = "//Chart/request/zip";

NodeList nodes = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

for(int i=0; i<nodes.getLength(); i++)
{
Node the_node = nodes.item(i);

if(the_node instanceof Element)
{
Element the_element=(Element) the_node;
System.out.println("element="+the_element.getTextContent());
break; // STOP at the first
}
}

关于Java解析XML以获取子元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34170865/

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