简体   繁体   中英

Reading the XML file in c#

I have the following XML file (parse.xml):

<Invoice>
    <InvoiceHeader>
          <Name>cust1</Name>
          <Number>5689</Number>
    </InvoiceHeader>
    <InvoiceHeader>
          <Name>cust1</Name>
          <Number>5689</Number>
          <Number>5459</Number>
    </InvoiceHeader>
<InvoiceHeader>
          <Name>cust1</Name>
          <Number>5689</Number>
          <Number>5645</Number>
          <Number>5879</Number>
    </InvoiceHeader>
</Invoice>

I would like to read it into a list of the following class:

public class Details    
{
   public string Name {get; set;}
   public List<string> Number{get; set;}
}

As you can see, in the XML the node Number can appear more than one time in InvoiceHeader . I'm not sure how to parse this XML into the List<Details> class.

I tried my code:

 List<Details> details = new List<Details>;
 XmlDocument doc = new XmlDocument();
 doc.Load("parse.xml");
 XmlNodeList nodeList = doc.SelectNodes("/Invoice/InvoiceHeader");

 foreach (XmlNode node in nodeList)
 {
     details.Add(node["Name"].InnerText);
     XmlNodeList dd = node.ChildNodes;

     foreach (XmlNode inch in dd)
     {
         details.Add(node["Number"].InnerText);
     }        
}

I know this code isn't right but wanted to show what I have done so far.

nodeList is a list of <InvoiceHeader> nodes. One method to solve this problem would be to iterate through the ChildNodes of nodeList and use the property Name to create the Details class in each iteration.

Your code was almost there... I've just updated it slightly so it correctly adds the <Number> elements to the list:

List<Details> detailsList = new List<Details>();
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodeList = doc.SelectNodes("/Invoice/InvoiceHeader");
foreach (XmlNode node in nodeList)
{
    // create details class for each InvoiceHeader
    Details detail = new Details();
    detail.Number = new List<string>();

    // loop over child nodes to get Name and all Number elements
    foreach (XmlNode child in node.ChildNodes)
    {  
        // check node name to decide how to handle the values               
        if (child.Name == "Name")
        {
            detail.Name = child.InnerText;
        }
        else if (child.Name == "Number")
        {
            detail.Number.Add(child.InnerText);
        }                    
    }
    detailsList.Add(detail);
} 

Then you can display the results like this:

foreach (var details in detailsList)
{
    Console.WriteLine($"{details.Name}: {string.Join(",", details.Number)}");
}

// output
cust1: 5689
cust1: 5689,5459
cust1: 5689,5645,5879

Another method you could consider is Linq-to-Xml . The below code produces the same output as that above:

XDocument doc = XDocument.Load(path);
var details =  doc.Descendants("Invoice")
                  .Elements()
                  .Select(node => new Details() 
                  { 
                      Name = node.Element("Name").Value, 
                      Number = node.Elements("Number").Select(child => child.Value).ToList() 
                  })
                  .ToList();

Please find below code attachment You need to follow this few steps using System.Xml; XmlTextReader reader = new XmlTextReader ("file name.xml");

while (reader.Read()) 
{
    // Do some work here on the data.
Console.WriteLine(reader.Name);
}
Console.ReadLine();
while (reader.Read()) 
{
    switch (reader.NodeType) 
    {
        case XmlNodeType.Element: // The node is an element.
            Console.Write("<" + reader.Name);
   Console.WriteLine(">");
            break;
  case XmlNodeType.Text: //Display the text in each element.
            Console.WriteLine (reader.Value);
            break;
  case XmlNodeType. EndElement: //Display the end of the element.
            Console.Write("</" + reader.Name);
   Console.WriteLine(">");
            break;
    }
}

while (reader.Read()) 
{
       switch (reader.NodeType) 
       {
           case XmlNodeType.Element: // The node is an element.
               Console.Write("<" + reader.Name);

               while (reader.MoveToNextAttribute()) // Read the attributes.
                   Console.Write(" " + reader.Name + "='" + reader.Value + "'");
      Console.WriteLine(">");
               break;
     case XmlNodeType.Text: //Display the text in each element.
               Console.WriteLine (reader.Value);
               break;
     case XmlNodeType. EndElement: //Display the end of the element.
               Console.Write("</" + reader.Name);
      Console.WriteLine(">");
               break;
       }
   }

finally save code and run them... Complete code listing

using System;
    using System.Xml;

    namespace ReadXMLfromFile
    {
        /// <summary>
        /// Summary description for Class1.
        /// </summary>
        class Class1
        {
            static void Main(string[] args)
            {
                XmlTextReader reader = new XmlTextReader ("file name.xml");
                while (reader.Read()) 
                {
                    switch (reader.NodeType) 
                    {
                        case XmlNodeType.Element: // The node is an element.
                            Console.Write("<" + reader.Name);
                            Console.WriteLine(">");
                            break;
                        case XmlNodeType.Text: //Display the text in each element.
                            Console.WriteLine (reader.Value);
                            break;
                        case XmlNodeType.EndElement: //Display the end of the element.
                            Console.Write("</" + reader.Name);
                            Console.WriteLine(">");
                            break;
                    }
                }
                Console.ReadLine();
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM