【问题标题】:Extracting from XML string从 XML 字符串中提取
【发布时间】:2013-07-22 12:25:28
【问题描述】:

如何编写一个程序来转换这个 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 可以让它变得更简单吗?

【问题讨论】:

标签: c# .net xml linq


【解决方案1】:

使用 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

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

【讨论】:

  • 你能把它概括为“循环”通过“boom”中的元素(不假设固定的“名称”和“地址”)吗?
  • 谢谢,这行得通。您能否添加另一个更新,允许我过滤掉满足某些任意条件的景气元素,例如其中address 包含“New”(在这种情况下只有“New York City”,并且只会出现第一个繁荣)?
  • 我为此创建了一个单独的问题,请随意试一试:stackoverflow.com/questions/17815090/…
猜你喜欢
  • 2013-05-02
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 2013-12-10
  • 2014-08-30
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多