簡體   English   中英

從XML字符串中提取

[英]Extracting from XML string

我如何編寫一個程序來轉換此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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM