0
我期待這樣的事情:我如何獲得一個XML節點作爲字符串中的內容在Java中
<Node1>
<Child2 attr1="abc">
<Child3 attr2="xyz">
<Node1>
從節點1,我想要得到的節點裏面的文字內容。我想輸出是
"<Child2 attr1="abc"><Child3 attr2="xyz">"
我期待這樣的事情:我如何獲得一個XML節點作爲字符串中的內容在Java中
<Node1>
<Child2 attr1="abc">
<Child3 attr2="xyz">
<Node1>
從節點1,我想要得到的節點裏面的文字內容。我想輸出是
"<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與其他可能的答案。
我正在使用DOM來執行此操作。 – Anon 2011-01-29 06:18:24