XML解析后,元素节点对象将转换为文本节点

时间:2017-01-24 10:08:13

标签: java xml dom xml-parsing w3c

我第一次运行这个程序时需要创建xml,我首先创建文件并创建一个Document对象,然后将其转换为Element对象。

        xmlDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        xmlDoc +="<head>";
        xmlDoc +=  "</head>";

        Document xmlFile =  XmlParser.parseXmlString(xmlDoc);
        Element element = xmlFile.getDocumentElement();

我已经用它的NodeType代码验证了这一点,但是当我创建父节点时,它给了我Element_Node == 1.我将这个节点附加到元素对象。

        Element newElement = xmlFile.createElement("parent");
        newElement.setAttribute("id", i);
        element.appendChild(newElement);

如果孩子不是父元素的孩子,我会把孩子放在父母身上,我检查一下,如果它不是孩子,我会创建一个新的Node类并给它文字内容。

            Node newChild = xmlFile.createElement("child");
            newChild.setTextContent(text);
            newElement.appendChild(newChild);

然后我会用变压器保存这个文件。

 Transformer transformer = null;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        DOMSource source = new DOMSource(xmlFile);
        StreamResult console = new StreamResult(System.out);
        try {
            transformer.transform(source, new StreamResult(new FileOutputStream(file.getPath())));
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

现在我第二次运行程序时,我会直接从这个文件解析。创建的XML文件具有以下结构

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<head>
<parent id="1">
<child>text1</child>
<child>text2</child>
<child>text3</child>
</parent>
<parent id="2">
<child>text1</child>
<child>text2</child>
</parent>
</head>

现在创建了文件,将读取文件然后解析以创建元素而不是硬编码字符串。

xmlDoc = this.readFile(file, Charset.forName("UTF-8"));
Document xmlFile =  XmlParser.parseXmlString(xmlDoc);
Element element = xmlFile.getDocumentElement();
...
 String readFile(File file, Charset charset) throws IOException {
        return new String(Files.readAllBytes(file.toPath()), charset);

问题是现在父元素不能作为元素生成,并且具有Text_Node类型值== 3.以下对象无法生成。

Element nextSib = (Element) element.getFirstChild();

我的想法是,现在我可以通过遍历每个父节点将相关子节点附加到父节点,这就是我需要以元素形式获取它的原因,因此我可以使用id属性。但是我不能这样做,因为父节点由于某种原因被转换为文本节点。

1 个答案:

答案 0 :(得分:1)

在写出树时使用缩进时,元素节点之间会有空格,因此子节点可以是带有空格的文本节点。如果您正在寻找第一个元素子节点,请使用XPath *[1]或仅使用元素foo[1]的名称,或者如果您想使用childNodes,请确保检查nodeType直到你有一个元素节点。

相关问题