gpt4 book ai didi

java - 将 XML 元素节点和文本节点放入字符串数组中

转载 作者:数据小太阳 更新时间:2023-10-29 02:12:39 24 4
gpt4 key购买 nike

请帮我将元素和文本节点放入一个 String 数组中。

例如,一个 .xml 文件有:

<soap:Envelope>
<soap:Body>
<ser:getTitle>
<!--Optional:-->
<ser:title>Meeting</ser:title>
</ser:getTitle>
<ser:getDiscription>
<!--Optional:-->
<ser:discription>this is the meeting</ser:discription>
</ser:getDiscription>
...
</soap:Body>
</soap:Envelop>

现在我想将值放入 String[] key, value 中,如下所示:

key[0] = "title";
value[0] = "meeting";
key[1] = "discription";
value[1] = "this is the meeting";

...等等。

非常感谢!

最佳答案

您可以使用 DOM解析您的输入 XML 并使用类似的东西:

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.File;

public dumpXMLTags(...) {
String[] keys; // you would need that with appropriate size initialized
String[] values;

// Parse your XML file and construct DOM tree
File fXmlFile = new File(PATH_TO_YOUR_XML_FILE);
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

// Traverse DOM tree (make sure is not empty first, etc)
NodeIterator iterator = traversal.createNodeIterator(
doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);

int i = 0; // index to you key/value Array

for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
keys[i] = ((Element) n).getTagName();
values[i] = ((Element)n).getNodeValue();
i++;
}
}

或者,您可以将 XPATH 与

一起使用
//@* | //*[not(*)]

表达式,如此处所述:Question 7199897

public static void main(String[] args) throws Exception {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));

XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
NodeList nodes = (NodeList)xp.evaluate("//@* | //*[not(*)]", doc, XPathConstants.NODESET);

System.out.println(nodes.getLength());

for (int i=0, len=nodes.getLength(); i<len; i++) {
Node item = nodes.item(i);
System.out.println(item.getNodeName() + " : " + item.getTextContent());
}
}

关于java - 将 XML 元素节点和文本节点放入字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12132831/

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