gpt4 book ai didi

java - Java中NodeList转字符串

转载 作者:行者123 更新时间:2023-12-03 15:58:25 40 4
gpt4 key购买 nike

我正在尝试将 NodeList 转换为 String 以便我可以以任何我想要的方式操作它,但我似乎无法在网上找到答案。

我试过将 NodeList 存储在一个 Node 数组中,但是打印出来的所有数据都是空的。

TextingXPath.java

import java.io.IOException;

public class TestingXPath {


static Node[] copy;
static int length;

public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException {

URL obj = new URL("http://jbossews-ashton.rhcloud.com/testXML.jsp");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();

if (responseCode == 200) {

DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
try {
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document dDoc = builder.parse(con.getInputStream());

XPath xPath = XPathFactory.newInstance().newXPath();

Node node = (Node) xPath.evaluate(
"/HDB/Resident[@Name='Batman ']/Preference", dDoc,
XPathConstants.NODE);
if (null != node) {
NodeList nodeList = node.getChildNodes();
for (int i = 0; null != nodeList
&& i < nodeList.getLength(); i++) {
Node nod = nodeList.item(i);
if (nod.getNodeType() == Node.ELEMENT_NODE)
{

...

}
}
}
} catch (Exception e) {
e.printStackTrace();
}

}

}

}

最佳答案

如果您只需要没有 XML 的内容,则此将节点转换为字符串它会按原样将节点作为 XML 获取 getTextContent

Node elem = nodeList.item(i);//Your Node
StringWriter buf = new StringWriter();
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // optional
xform.setOutputProperty(OutputKeys.INDENT, "yes"); // optional
xform.transform(new DOMSource(elem), new StreamResult(buf));
System.out.println(buf.toString()); // your string

关于java - Java中NodeList转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31399798/

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