简体   繁体   中英

DOM XML: Write to file and read it again

I'm generating XML file using DOM.

public void save() 
{
    if(readonly)
    {
        throw new WritingToLockedFileException();
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(fileInfo);
        StreamResult result = new StreamResult(fileXML);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes"); 
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(source, result);
        System.out.println("File saved!");
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

When I'm using

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"yes"); 
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

then I'm getting [#text, lock, #text, testing, #text] instead of [lock, testing] which I get, when I comment those 3 lines. Does anybody know how can i generate human-readable XML file, that can be re-readed by the DOM parser.

That list I'm getting using this function:

public List<String> getTags() 
{
    Element summary = (Element) fileInfo.getElementsByTagName("summary").item(0);
    Element tags = (Element) summary.getElementsByTagName("tags").item(0);
    NodeList list = tags.getChildNodes();
    List<String> taglist = new ArrayList<String>();
    for(int i=0; i<list.getLength(); i++)
    {
        taglist.add(list.item(i).getNodeName());
    }
    return taglist;
}

and the XML human-readable xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<summary>
    <tags>
        <lock/>
        <testing/>
    </tags>
</summary>

What you see as #text nodes are just text spaces between tags (new lines and indentations). In general you might want to use these text blocks in some way (if there is more than just spaces). But as long as you don't need to use them in your case just add skipping check for these nodes into the for loop forming taglist:

    for (int i=0; i<list.getLength(); i++) {
        org.w3c.dom.Node elem = list.item(i);
        if (elem.getNodeType() == org.w3c.dom.Node.TEXT_NODE && 
                elem.getNodeValue().trim().isEmpty()) {
            continue;
        }
        taglist.add(elem.getNodeName());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM