如何从另一个 xml 更改层次结构序列化 android 中的 xml
我有这个源 xml:
<source>
<category id="1" />
<item1 />
<item2 />
<category id="2"/>
<item1 />
<item2 />
</source>
如您所见,所有项目都具有相同的层次结构。 我需要将其“翻译”/序列化为另一个 XML,如下所示:
<source>
<category id="1">
<item1 />
<item2 />
</category>
<category id="2">
<item1 />
<item2 />
</category>
</source>
其中“items”是“category”的子级。
兼容,我不介意使用另一个
我正在使用 Android 工具中的 XmlPullParser 和 XmlSerializer,但如果它们与 Android 环境Tx
I've got this source xml:
<source>
<category id="1" />
<item1 />
<item2 />
<category id="2"/>
<item1 />
<item2 />
</source>
As you can see all items have the same hierarchy.
And I need to "translate"/serialize it to another XML like this:
<source>
<category id="1">
<item1 />
<item2 />
</category>
<category id="2">
<item1 />
<item2 />
</category>
</source>
Where "items" are children of "category".
I'm using XmlPullParser and XmlSerializer from Android tools but I don't mind to use another if they are compatible with Android environment
Tx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了另一种使用 XSLT 的方法:
通过这种方式,我们可以使用仅 XML 的特定工具进行转换,而不用对象处理任何数据。
创建一个transform.xsl 文件来处理转换:
然后将处理转换的代码编写到具有所需输出data.xml 的文件中
,就完成了。
更多信息在这里:
http://www.dpawson.co.uk/xsl/sect2/flatfile.html
I've found another way using XSLT:
This way we use XML-only specific tools for transform without handling any data with objects.
create a transform.xsl file to handle transformation:
And then write the code to handle transformation to a file with desired output data.xml
And its done.
more info here:
http://www.dpawson.co.uk/xsl/sect2/flatfile.html
对于简单的 xml 格式来说,这应该不难。
使用 sax 解析器读取第一个 xml 文件的一种可能方法是:
对于每个
标记,您创建一个新的Category
对象。以下项目将添加到最后一个类别对象中。在阅读内容时,您可以创建稍后需要的层次结构(项目将添加到适当的类别)。将此代码转换为使用 XmlPullParser 而不是 sax 解析器应该很容易。我只是用萨克斯,因为我更熟悉它。
读完第一个文件后,您需要将层次结构写入新文件。
您可以通过如下方式执行此操作:
每个类别的
getXml()
可能如下所示:每个项目在其
getXml()
方法中创建自己的 xml,该方法可能位于最简单的情况。
请注意,只有当您的 xml 结构保持那么简单时,手动构建 xml 才合适。如果结构变得更加复杂,您应该使用一些适用于 Android 的轻量级 xml 库(例如 xstream) 。
For an easy xml format this shouldn't be that hard.
A possible way to read the first xml file with a sax parser would be:
For each
<category>
tag you create a newCategory
object. The following items will be added to the last category object. While reading the contents you create the hierarchy you need later (items are added to the appropriate category).It should be easy to transform this code to use XmlPullParser instead of sax parser. I just used sax because I am more familiar with it.
When you finished reading the first file you need to write your hierarchy to a new file.
You can do this in a way like this:
getXml()
for each category could look like:Each item creates its own xml in its
getXml()
method which could bein the easiest case.
Please note that building xml by hand is only suitable if you xml structure stays that simple. If the structure is becoming more complicated you should make use of some lightweight xml libraries that work on Android (like xstream).