本文介绍了从XML字符串中提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何编写一个程序来打开这个XML字符串
How can I write a program that turns this XML string
<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可以使其更容易?
Can LINQ make it easier?
推荐答案
使用LINQ到XML:
With 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
更新
要在任何元素概括它热潮
,这个想法是一样的。
Update
To generalize it with any elements in boom
, the idea is the same.
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
第一行和最后一行保持相同。
The first and last lines remains the same.
这篇关于从XML字符串中提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!