java Java中NodeList转字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31399798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting NodeList to String in Java
提问by Ashton
I'm trying to convert NodeList to String so I can manipulate it in whichever way I want, but I can't seem to find an answer online.
我正在尝试将 NodeList 转换为 String 以便我可以以任何我想要的方式操作它,但我似乎无法在网上找到答案。
I've tried storing the NodeList in a Node array, but all the data printed out would be null.
我试过将 NodeList 存储在一个 Node 数组中,但是打印出来的所有数据都是空的。
TextingXPath.java
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();
}
}
}
}
}
回答by Ali Helmy
This Convert Node to String it gets the node as XML as is, if you need only the content with no XML use getTextContent
如果您只需要不使用 XML 的内容,则此 Convert Node to String 将节点按原样获取为 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
回答by Raghavendra
For printing Preference1
elements
用于印刷Preference1
元素
use System.out.println(nod.getTextContent());
利用 System.out.println(nod.getTextContent());
回答by Shubham Mehta
you can print the node names as follows
您可以按如下方式打印节点名称
System.out.println(node.getNodeName());