我正在尝试将 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)