1
將xml node
轉換爲xml string
時出現錯誤。我想獲得SDG節點並將其轉換爲xml String
,但我得到的僅僅是一個空字符串。從java中的節點獲取xml字符串時出現空字符串
這是來源:
public class StringToDocumentToString {
public static void main(String[] args) {
Document doc = convertStringToDocument();
String str = convertDocumentToString(doc.getDocumentElement().getFirstChild());
System.out.println(str);
}
private static String convertDocumentToString(Node doc) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
// below code to remove XML declaration
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
private static Document convertStringToDocument() {
File fXmlFile = new File("C:\\data.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse(fXmlFile);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
和XML數據:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:data key="SDG" xmlns:ns2="http:my.example.com" xmlns:xmime="http://www.w3.org/2005/05/xmlmime">
<SDG SI="General" xmlns="http:my.example.com">
<SD SI="Classification">EventOrderTest</SD>
<SD SI="RequiredInterfaces">None</SD>
</SDG>
</ns2:data>
什麼是錯我的代碼?我錯過了什麼嗎?
在此先感謝。
解決:
按照greenPadawan的解決方案:
使用 「convertDocumentToString(doc.getFirstChild())」,而不是 「convertDocumentToString(doc.getDocumentElement()getFirstChild() )」。
#greenPadawan:如果使用convertDocumentToString(doc.getFirstChild()),結果與原始xml數據相同。我只想獲得SDG。 – nguyenmy
然後你可以在你的convertDocumentToString方法中傳遞節點SDG。像convertDocumentToString(doc.getFirstChild()。getChildNodes()。item(1))。在這個語句中,「1」是節點SDG的索引,在節點的子節點列表中。 –
greenPadawan
#greenPadawan:非常感謝,它工作得很好。 – nguyenmy