gpt4 book ai didi

java - 如何在 Java 中以字符串形式获取 XML 节点内的内容

转载 作者:行者123 更新时间:2023-12-01 15:57:19 25 4
gpt4 key购买 nike

我正在寻找这样的东西:

<Node1>
<Child2 attr1="abc">
<Child3 attr2="xyz">
<Node1>

从 Node1 中,我想以文本形式获取节点内的内容。我想要的输出是

"<Child2 attr1="abc"><Child3 attr2="xyz">"

最佳答案

   //Parse the input document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("yourfile.xml"));

//Set up the transformer to write the output string
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);

//Find the first child node
NodeList nl = doc.getDocumentElement().getChildNodes();
DOMSource source = null;
for(int x = 0;x < nl.getLength();x++)
{
Node e = nl.item(x);
if(e instanceof Element)
{
source = new DOMSource(e);
break;
}
}

transformer.transform(source, result);
System.out.println(sw.toString());
}
}

查看此question以及其他可能的答案。

关于java - 如何在 Java 中以字符串形式获取 XML 节点内的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4835478/

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