我如何将XML转换为一个List&LT;串GT;或字符串[]? [英] How can I transform XML into a List<string> or String[]?
问题描述
我怎么能转换下面的XML到列表&LT;串&GT;
或的String []
:
&LT; IDS&GT;
&LT; ID&GT; 1 LT; / ID&GT;
&LT; ID&GT; 2'; / ID&GT;
&LT; / IDS&GT;
这听起来像你只是解析,而不是完整的XML序列化/反序列化后多。如果你可以使用LINQ到XML,这是pretty容易:
使用系统;
使用System.Linq的;
使用System.Xml.Linq的;公共类测试
{
静态无效的主要()
{
字符串XML =&LT; IDS&GT;&LT; ID&GT; 1&LT; / ID&GT;&LT; ID&GT; 2&LT; / ID&GT;&LT; / IDS&gt;中; 的XDocument文档= XDocument.Parse(XML); VAR列表= doc.Root.Elements(ID)
。选择(元=&GT; element.Value)
.ToList(); 的foreach(列表中的字符串值)
{
Console.WriteLine(值);
}
}
}
事实上,因为调用元素
可以省略该参数是的仅 ID
元素,但我想我会演示如何指定你想要的元素。
同样我通常不打扰调用 了ToList
除非我真的需要一个列表&LT;串&GT;
- 没有它,结果是的IEnumerable&LT;串&GT;
这是好的,如果你只是遍历一次。要创建一个数组而是使用 的ToArray
。
How can I transform the following XML into a List<string>
or String[]
:
<Ids>
<id>1</id>
<id>2</id>
</Ids>
It sounds like you're more after just parsing rather than full XML serialization/deserialization. If you can use LINQ to XML, this is pretty easy:
using System;
using System.Linq;
using System.Xml.Linq;
public class Test
{
static void Main()
{
string xml = "<Ids><id>1</id><id>2</id></Ids>";
XDocument doc = XDocument.Parse(xml);
var list = doc.Root.Elements("id")
.Select(element => element.Value)
.ToList();
foreach (string value in list)
{
Console.WriteLine(value);
}
}
}
In fact the call to Elements
could omit the argument as there are only id
elements, but I thought I'd demonstrate how to specify which elements you want.
Likewise I'd normally not bother calling ToList
unless I really needed a List<string>
- without it, the result is IEnumerable<string>
which is fine if you're just iterating over it once. To create an array instead, use ToArray
.
这篇关于我如何将XML转换为一个List&LT;串GT;或字符串[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!