How to read XML file in c#?

2019-06-22 06:10发布

I have following XML file, i want to know best way to read this XML file

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

As an output i need collection of values like "123,456,789" or it could be array of string[]

Can we use Linq to xml? How?

6条回答
贪生不怕死
2楼-- · 2019-06-22 06:15

In dataset you can read xml file

Following are lines of code to read XML file in DataSet

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 
查看更多
乱世女痞
3楼-- · 2019-06-22 06:16
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);
}
查看更多
Evening l夕情丶
4楼-- · 2019-06-22 06:17

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;
    }
}
查看更多
男人必须洒脱
5楼-- · 2019-06-22 06:21
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);
查看更多
Root(大扎)
6楼-- · 2019-06-22 06:26

Use LINQ to XML, Include 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);

Output would be:

123,456,789

查看更多
太酷不给撩
7楼-- · 2019-06-22 06:37
var xdoc = XDocument.Load(PATH_TO_FILE);
var companies = xdoc.Descendants("Company").Select(c => (string)c).ToArray();

This will give you a string[].

查看更多
登录 后发表回答