是否有用于非连续创建XML的内置Android类?

时间:2014-01-23 19:03:17

标签: java android xml

我写了一个没有取得多大成功的问题:https://stackoverflow.com/questions/21296465/serialize-hashmap-as-xml-without-repeating-parent-elements。在我看来,也许我在问错误的问题。

是否有用于非连续创建XML的内置Android类?

非连续,我的意思是能够操纵现有元素(添加/删除子等)。到目前为止,我已经找到了创建XML的方法(XmlSerializer,构建字符串),但只能在连续文档中使用。

这是我正在寻找的伪代码:

[...]
//Note: Element is not a real class, but I'm guessing there will need to be a class that handles adding/removing other attributes, values, and other Elements.

//add necessary header for XML
xmldoc.startXML(); 

// this creates and returns an Element representing "<object></object>" 
Element rootNode = xmldoc.addElement("object", ""); 

//this inserts "<key>key1</key>" into "<object></object>" and returns itself
Element key1 = rootNode.addChildElement("key", "key1"); 
//this inserts "<value>value1</value>" into "<object></object>" but I don't care about setting it as a variable for later use.
rootNode.addChildElement("value", "value1");

[...]

//write the XML as a String/Stream/Something (called handler here).
xmldoc.flush(handler);

通过一些额外的逻辑,这些函数可以创建以下XML

<object>
    <key>root</key>
    <object>
        <key>key1</key>
        <value>value1</value>
    </object>
    <object>
        <key>key2</key>
        <value>value2</value>
    </object>
    <object>
        <key>ns</key>
        <object>
            <key>key3</key>
            <value>value3</value>
        </object>
        <object>
            <key>key4</key>
            <value>value4</value>
        </object>
    </object>
</object>

2 个答案:

答案 0 :(得分:1)

确实你必须坚持XML DOM processing,整个文档存储在RAM中,允许你随机读/写它的节点和属性。 XPath帮助遍历xml-tree

答案 1 :(得分:0)

在开始创建自己的课程后,我再次开始谷歌搜索,我找到了我想要的东西。它实际上与我的伪代码非常相似。这些类使用org.w3c.dom和javax.xml.parsers.DocumentBuilder它在http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/概述。

[...]
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
[...]
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

//New Document
Document doc = docBuilder.newDocument();

// root element
Element rootElement = doc.createElement("object");
doc.appendChild(rootElement);

Element child = doc.createElement("object");
doc.appendChild(rootElement);

// key element
Element key = doc.createElement("key");
key.appendChild(doc.createTextNode("key1"));
child.appendChild(key);

// value element
Element value = doc.createElement("value");
value.appendChild(doc.createTextNode("value1"));
child.appendChild(value);

创建:

<object>
    <key>root</key>
    <object>
        <key>key1</key>
        <value>value1</value>
    </object>
</object>