我寫了一個沒有太多成功的問題:https://stackoverflow.com/questions/21296465/serialize-hashmap-as-xml-without-repeating-parent-elements。我想到,也許我在問錯誤的問題。是否有內置的Android類用於非連續創建XML?
是否有一個內置的Android類用於非連續創建XML?
通過非連續,我的意思是能夠操縱現有的元素(添加/刪除兒童等)。到目前爲止,我已經找到了創建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>
可以在仍處於內存中時使用帶有DOM寫入的XPath嗎?我認爲XPath只是用於解析,而不是寫作。 – Tim
只能在內存中使用XPath! XPath旨在用於搜索特定節點,而不是解析。有很多關於該主題的信息和示例,例如這裏http://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java – injecteer
謝謝。我在記憶中的意思並不是說,我的意思是在解碼而不是編碼時。但現在它很有意義。 – Tim