C# 如何将 XML 转换为 List<string> 或 String[]?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/956749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:13:49  来源:igfitidea点击:

How can I transform XML into a List<string> or String[]?

c#xmlxml-serialization

提问by Henry B

How can I transform the following XML into a List<string>or String[]:

如何将以下 XML 转换为List<string>or String[]

<Ids>
  <id>1</id>
  <id>2</id>
</Ids>

采纳答案by Jon Skeet

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:

听起来你只是在解析而不是完整的 XML 序列化/反序列化之后。如果您可以使用 LINQ to XML,这将非常简单:

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 Elementscould omit the argument as there areonly idelements, but I thought I'd demonstrate how to specify which elements you want.

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

Likewise I'd normally not bother calling ToListunless 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.

同样,ToList除非我真的需要,否则我通常不会打电话给List<string>- 没有它,IEnumerable<string>如果您只是迭代一次,结果很好。要改为创建数组,请使用ToArray.

回答by jjxtra

This sample will work with the .NET framework 3.5:

此示例适用于 .NET 框架 3.5:

    System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse("<Ids>  <id>1</id>  <id>2</id></Ids>");
    System.Collections.Generic.List<string> ids = new System.Collections.Generic.List<string>();
    foreach (System.Xml.Linq.XElement childElement in element.Descendants("id"))
    {
        ids.Add(childElement.Value);
    }

回答by Martin Delille

Here is a way using XmlDocument :

这是使用 XmlDocument 的一种方法:

// A string containing the XML data
string xml = "<Ids><id>1</id><id>2</id></Ids>";
// The list you want to fill
ArrayList list = new ArrayList();

XmlDocument doc = new XmlDocument();
// Loading from a XML string (use Load() for file)
doc.LoadXml(xml); 
// Selecting node using XPath syntax
XmlNodeList idNodes = doc.SelectNodes("Ids/id");
// Filling the list
foreach (XmlNode node in idNodes)
    list.Add(node.InnerText);

回答by shake

You can use Properties class.

您可以使用 Properties 类。

Properties prop = new Properties();
prop.loadFromXML(stream);
Set set = prop.keySet();

You can than access Strings from set for each key. Key is element name of xml.

您可以从每个键的集合中访问字符串。Key 是 xml 的元素名称。

回答by AareP

Here's a way to get typed array from xml by using DataSets. (in this example array of doubles)

这是一种使用 DataSet 从 xml 获取类型化数组的方法。(在这个例子中双打数组)

DataSet dataSet = new DataSet()
DoubleArray doubles = new DoubleArray(dataSet,0);

dataSet.ReadXml("my.xml");
double a = doubles[0];



public class DoubleArray
{
  DataSet dataSet;
  int tableIndex;
  public DoubleArray(DataSet dataSet,int tableIndex)
  {
    this.dataSet=dataSet;
    this.tableIndex=tableIndex;
  }

  public double this[int index]
  {
    get
    { 
      object ret = dataSet.Tables[tableIndex].Rows[index];
      if(ret is double?) 
        return (ret as double?).Value;
      else
        return double.Parse(ret as string);
    }
    set
    {
      object out = dataSet.Tables[tableIndex].Rows[index];
      if(out is double?)
        dataSet.Tables[tableIndex].Rows[index] = (double?)value;
      else
        dataSet.Tables[tableIndex].Rows[index] = value.ToString();
    }
  }
}

Of course parsing doubles and converting them back to strings all the time might be considered as blasphemy by some programmers... Even for me it was hard not to think about such waste of resources... but I guess sometimes it's better to just turn another away.. don't stress it :)

当然,一直解析双打并将它们转换回字符串可能会被一些程序员认为是亵渎......即使对我来说也很难不考虑这种资源浪费......但我想有时最好只是转另一个离开..不要强调它:)

回答by ehsan

the code to convert a string array to xml

将字符串数组转换为 xml 的代码

items is a string array

items 是一个字符串数组

items.Aggregate("", (current, x) => current + ("<item>" + x + "</item>"))

回答by Dom

This sample will work with the .NET framework 4.0:

此示例适用于 .NET 框架 4.0:

into a List

成一个列表

    List<string> Ids= new List<string>(); 
    Ids= selectedNode.Descendants("Ids").Elements("Id").Select(> x=>x.Value).Where(s =>s!= string.Empty).ToList();

into a string []

变成一个字符串 []

    string[] Ids= thisNode
                  .Descendants("Ids")          // Ids element
                  .Elements("Id")              // Id elements
                  .Select(x=>x.Value)          // XElement to string
                  .Where(s =>s!= string.Empty) // must be not empty
                  .ToArray();                  // string to string []

回答by Dom

With any type of collection. For example :

与任何类型的集合。例如 :

<Ids><id>C:\videotest\file0.txt</id><id>C:\videotest\file1.txt</id></Ids>

<Ids><id>C:\videotest\file0.txt</id><id>C:\videotest\file1.txt</id></Ids>

class FileFormat
    {
        public FileFormat(string path)
        {
            this.path = path;
        }
        public string FullPath
        {
            get { return Path.GetFullPath(path); }
        }
        public string FileName
        {
            get { return Path.GetFileName(path); }
        }
        private string path;
    }

List<FileFormat> Files =
        selectedNode
        .Descendants("Ids")
        .Elements("Id")
        .Select(x => new FileFormat(x.Value))
        .Where(s => s.FileName!=string.Empty)
        .ToList();