我如何将XML转换为一个List<串GT;或字符串[]? [英] How can I transform XML into a List<string> or String[]?

查看:79
本文介绍了我如何将XML转换为一个List<串GT;或字符串[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能转换下面的XML到列表<串> 的String []

 < IDS>
  < ID> 1 LT; / ID>
  < ID> 2'; / ID>
< / IDS>


解决方案

这听起来像你只是解析,而不是完整的XML序列化/反序列化后多。如果你可以使用LINQ到XML,这是pretty容易:

 使用系统;
使用System.Linq的;
使用System.Xml.Linq的;公共类测试
{
    静态无效的主要()
    {
        字符串XML =< IDS>< ID> 1< / ID>< ID> 2< / ID>< / IDS>中;        的XDocument文档= XDocument.Parse(XML);        VAR列表= doc.Root.Elements(ID)
                           。选择(元=> element.Value)
                           .ToList();        的foreach(列表中的字符串值)
        {
            Console.WriteLine(值);
        }
    }
}

事实上,因为调用元素可以省略该参数是的仅 ID 元素,但我想我会演示如何指定你想要的元素。

同样我通常不打扰调用 了ToList 除非我真的需要一个列表<串> - 没有它,结果是的IEnumerable<串> 这是好的,如果你只是遍历一次。要创建一个数组而是使用 的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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆