gpt4 book ai didi

java - 从java中的节点获取xml字符串时出现空字符串

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:45 25 4
gpt4 key购买 nike

xml 节点 转换为 xml 字符串 时出现错误。我想获取 SDG 节点并将其转换为 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的解决方案:

use "convertDocumentToString(doc.getFirstChild())" instead of "convertDocumentToString(doc.getDocumentElement().getFirstChild())".

最佳答案

在主方法中,使用“convertDocumentToString(doc.getFirstChild())”而不是“convertDocumentToString(doc.getDocumentElement().getFirstChild())”。

关于java - 从java中的节点获取xml字符串时出现空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35762504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com