【发布时间】:2012-03-02 04:25:00
【问题描述】:
我目前正在尝试在 C# 中展平深度结构化的 XML 文档,以便将元素的每个值都转换为属性。
XML结构如下:
<members>
<member xmlns="mynamespace" id="1" status="1">
<sensitiveData>
<notes/>
<url>someurl</url>
<altUrl/>
<date1>somedate</date1>
<date2>someotherdate</date2>
<description>some description</description>
<tags/>
<category>some category</category>
</sensitiveData>
<contacts>
<contact contactId="1">
<contactPerson>some contact person</contactPerson>
<phone/>
<mobile>mobile number</mobile>
<email>some@email.com</email>
</contact>
</contacts>
</member>
</members>
我希望它看起来像这样:
<members>
<member xmlns="mynamespace" id="1" status="1" notes="" url="someurl" altUrl="" date1="somedate" date2="someotherdate" description="some description" tags="" category="some category" contactId="1" contactPerson="some contact person" phone="" mobile="mobile number" email="some@email.com" />
</members>
我可以只解析元素名称及其属性,但由于这个 XML 来自我无法控制的 web 服务,我必须创建某种动态解析器来将其展平,因为结构 可以 在某个时候改变。
值得注意的是,XML 结构来自 web 服务的 XElement。
以前有没有人尝试过这样做,并且可以帮助分享一下方法? :-) 将不胜感激!
非常感谢。
一切顺利,
博
【问题讨论】:
-
您显示的 XML 无效(
/kontakter没有开始标签?)...至于您的问题,没有一般答案,因为这完全取决于您要应用的规则(例如如果有多个contact等会发生什么)。我的问题是:你为什么要“扁平化”这个 XML? -
嗨 Yahia,谢谢 - 这只是一个错字 :) 我需要将其展平才能将其导入 CMS。
-
那么恕我直言,XSLT 是可行的方法,因为它允许在部署后更改转换规则...
标签: c# xml parsing xml-parsing