c# - 展平 XML 文档

标签 c# xml parsing xml-parsing

我目前正在尝试用 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 来 self 无法控制的 Web 服务,我必须创建某种动态解析器​​来将其展平为结构 在某些时候改变。

值得注意的是,XML 结构作为来自网络服务的 XElement。

有没有人以前尝试过这样做并且会有助于分享如何做? :-) 将不胜感激!

非常感谢。

祝一切顺利

最佳答案

试试这个:

var doc = XDocument.Parse(@"<members>...</members>");

var result = new XDocument(
    new XElement(doc.Root.Name,
        from x in doc.Root.Elements()
        select new XElement(x.Name,
            from y in x.Descendants()
            where !y.HasElements
            select new XAttribute(y.Name.LocalName, y.Value))));

结果:

<members>
  <member notes="" url="someurl" altUrl="" date1="somedate" date2="someotherdate" description="some description" tags="" category="some category" contactPerson="some contact person" phone="" mobile="mobile number" email="some@email.com" xmlns="mynamespace" />
</members>

关于c# - 展平 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9215273/

相关文章:

C# - 对象组合 - 删除样板代码

xml - 如何使用 JAXB 解析带有命名空间的 XML

python - 如何根据特殊条件去除文本文件每一行中的变量空间 - Python 中的单行?

parsing - 哪种 Haskell 解析技术最好用,为什么?

java - 如何使用 Univocity 例程验证 CSV header ?

c# - 确保文件上传到 Google Drive C#

c# - 制作井字游戏的领域模型

java - 模拟器: Process finished with exit code -1073741511 (0xC0000139) Andrioid Studio

c# - 引发 QuotaExceededException 的 WCF 文件传输服务

java - Android 图表如何删除垂直侧线?尝试了一切