c# - 从 XML 字符串中提取

标签 c# .net xml linq

如何编写一个程序来转换这个 XML 字符串

<outer>
  <inner>
    <boom>
      <name>John</name>
      <address>New York City</address>
    </boom>

    <boom>
      <name>Daniel</name>
      <address>Los Angeles</address>
    </boom>

    <boom>
      <name>Joe</name>
      <address>Chicago</address>
    </boom>
  </inner>
</outer>

进入这个字符串

name: John
address: New York City

name: Daniel
address: Los Angeles

name: Joe
address: Chicago

LINQ 能让它变得更简单吗?

最佳答案

使用 Linq-to-XML:

XDocument document = XDocument.Load("MyDocument.xml");  // Loads the XML document with to use with Linq-to-XML

var booms = from boomElement in document.Descendants("boom")  // Go through the collection of boom elements
            select String.Format("name: {0}" + Environment.NewLine + "address: {1}",  // Format the boom item
                                 boomElement.Element("name").Value,  // Gets the name value of the boom element
                                 boomElement.Element("address").Value);  // Gets the address value of the boom element

var result = String.Join(Environment.NewLine + Environment.NewLine, booms);  // Concatenates all boom items into one string with

更新

boom中的任何元素来概括它,思想是一样的。

var booms = from boomElement in document.Descendants("boom")  // Go through the collection of boom elements
            let boolChildren = (from boomElementChild in boomElement.Elements()  // Go through the collection of elements in the boom element
                                select String.Format("{0}: {1}",  // Formats the name of the element and its value
                                                     boomElementChild.Name.LocalName,  // Name of the element
                                                     boomElementChild.Value))  // Value of the element
            select String.Join(Environment.NewLine, boolChildren);  // Concatenate the formated child elements

第一行和最后一行保持不变。

关于c# - 从 XML 字符串中提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17810102/

相关文章:

java - Java解析XML时保留 `&#10; &#13;`等数字字符实体字符

c# - 如何在自定义 WebViewPage 中设置属性?

c# - 无法在 WCF REST 服务中反序列化 XML

c# - 如何将谓词传递给 linq 表达式

c# - 如何使用 LINQ to SQL 和 DbLinq 选择空值?

java - JAXB 更改默认命名转换器

Python ElementTree 对 HTML 实体进行转义

c# - TimoutException 发生在网络上而不是本地

.net - iTextSharp - 使用表格时文档没有页面

c# - 如何通过分配新集合来更新多对多集合?