从java中的节点获取xml字符串时为空字符串

时间:2016-03-03 03:13:34

标签: java xml

xml node转换为xml string时出错。我想获得SDG节点并将其转换为xml String,但我得到的只是一个空字符串。

这是来源:

 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的解决方案:

  

使用&#34; convertDocumentToString(doc.getFirstChild())&#34;代替   &#34; convertDocumentToString(doc.getDocumentElement()getFirstChild()。)&#34;

1 个答案:

答案 0 :(得分:0)

在main方法中,使用&#34; convertDocumentToString(doc.getFirstChild())&#34;而不是&#34; convertDocumentToString(doc.getDocumentElement()。getFirstChild())&#34;。