5

我有以下 XML 文件,我想知道阅读此 XML 文件的最佳方法

<MyFile> 
  <Companies> 
    <Company>123</Company> 
    <Company>456</Company>
    <Company>789</Company> 
  </Companies> 
</MyFile>

作为输出,我需要像“123,456,789”这样的值的集合,或者它可以是字符串数组[]

我们可以使用 Linq to xml 吗?如何?

4

6 回答 6

11
var xdoc = XDocument.Load(PATH_TO_FILE);
var companies = xdoc.Descendants("Company").Select(c => (string)c).ToArray();

This will give you a string[].

于 2012-06-27T11:25:12.617 回答
6

使用 LINQ to XML,包括using System.Xml.Linq;

   XDocument xmlDoc = XDocument.Load("yourfile.xml");
   var test = xmlDoc.Descendants("Companies").Elements("Company").Select(r => r.Value).ToArray();
   string result = string.Join(",", test);

输出将是:

123,456,789

于 2012-06-27T11:25:45.720 回答
4

在数据集中,您可以读取 xml 文件

以下是在 DataSet 中读取 XML 文件的代码行

DataSet dsMenu = new DataSet(); //Create Dataset Object

dsMenu.ReadXml("XMLFILENAME.XML"); // Read XML file in Dataset

DataTable dtXMLFILE// Create DatyaTable object

dtXMLFILE= dsMenu.Tables[0]; // Store XML Data in Data Table 
于 2012-06-27T12:01:22.343 回答
3
var xmlStr=@"<MyFile> 
  <Companies> 
    <Company>123</Company> 
    <Company>456</Company>
    <Company>789</Company> 
  </Companies> 
</MyFile>";

var xDoc = XDocument.Parse(xmlStr);
var companyIds = xDoc.Descendants("Company").Select(e => (int)e);
于 2012-06-27T11:24:41.880 回答
3
string pathToXmlFile = @"C:\test.xml";
XElement patternDoc = XElement.Load(pathToXmlFile);
List<string> values = new List<string>();
foreach (var element in patternDoc.Elements("Companies").Elements("Company"))
{
   values.Add(element.Value);
}
于 2012-08-15T06:53:36.003 回答
2

In the past, I have used an XmlReader and had no difficulties.

MSDN Documentation: http://msdn.microsoft.com/en-us/library/system.xml.xmlreader(v=vs.110).aspx

It is very straightforward and the documentation is pretty well written. A quick demonstration of how to use it:

XmlReader reader = XmlReader.Create(targetFile);

while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element:
            if (reader.Name.Equals("Company")
            {
                // Read the XML Node's attributes and add to string
            }
            break;
    }
}
于 2012-06-27T17:18:31.047 回答