[英]Java Document is null when printing but is saved correctly as Xml
I'm converting a String to an XML, this way: 我正在将String转换为XML,这样:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document doc = null;
try {
doc = builder.parse(new InputSource(new StringReader(xmlSource)));
} catch (SAXException | IOException e) {
e.printStackTrace();
}
I've tried printing a node or something to see how to retrieve node informations but it keeps printing null whenever I try doc.getNodeName()
or doc.getElementById(elementId)
, or whatever. 我已经尝试打印节点或其他东西,看看如何检索节点信息,但每当我尝试
doc.getNodeName()
或doc.getElementById(elementId)
或其他任何东西时,它都会一直打印null。
After this conversion I do this: 转换后,我这样做:
// Write the parsed document to an xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer= null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("TestFile.xml"));
try {
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
My TestFile.xml
is a correct XML file. 我的
TestFile.xml
是一个正确的XML文件。 So I don't understand why my Document is null. 所以我不明白为什么我的Document是null。 I need to retrieve informations from the document but this way I'm not able to do anything.
我需要从文档中检索信息,但这样我就无法做任何事情了。 If the XML file created and saved to disk is correct, how can he Document return null with every method?
如果创建并保存到磁盘的XML文件是正确的,那么Document如何使用每种方法返回null? What am I missing?
我错过了什么?
Please check my solution: App.java class 请检查我的解决方案: App.java类
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.