简体   繁体   中英

Read xml from file

I got a little problem with reading information from an xml file...

The file passed to me has thousands of lines. Im interested in only 300 - 400 of those lines. I don't need to write any data back to xml when the user is finished with his operation and the data to read can be stored in a List<string> .

I found solutions on the net using an XmlTextReader to read the data. So I wouldnt have to create a class and use a Serializer. But it seems like im using the XmlTextReader wrong. Maybe you can help me...

This is how the xml looks like:

<?xml version="1.0" encoding="utf-8"?>
<ProjectConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ProjectLists xmlns="...">
    <ProjectList>
  ... // not interested in this data
   </ProjectList>
  <ProjectList>
  <ListNode>
    <Name>Test_Environment</Name>
    <Children>
      <ListNode>
        <Name>yyy</Name>
        <Children>
          <ListNode>
            <Name>205 (ST)</Name>
            <Children>
              <ListNode>
                <Name>098-0031</Name>
                <Children />
              </ListNode>
              <ListNode>
                <Name>098-0032</Name>
                <Children />
              </ListNode>
              //more ListNodes...
            </Children>
          </ListNode>
          <ListNode>
            <Name>old</Name>
            <Children>
              <ListNode>
                <Name>W098-32</Name>
                <Children />
              </ListNode>
            </Children>
          </ListNode>
        </Children>
      </ListNode>
      <ListNode>
        <Name>xxx</Name>
        <Children />
      </ListNode>
      <ListNode>
        <Name>098-0001</Name>
        <Children />
      </ListNode>
      <ListNode>
        <Name>098-0011</Name>
        <Children />
      </ListNode>
      // More List Nodes
    </Children>
  </ListNode>
  <ListNode>
    // more List Nodes
  </ListNode>
</ProjectList>
<ProjectList>
  //more uninteresting ProjectLists...
</ProjectList>

I'm only interested in the Value of the most inner Name Elements (The first two would be "098-0031" and "098-0032").

And this is my code:

while (reader.Read()) {
            switch (reader.NodeType) {
                case XmlNodeType.Element:
                    {
                        if (reader.Name == "Name") {
                            reader.Read();
                            if (reader.Value == "Test_Environment") {
                                reader.ReadToDescendant("Children");
                                if (reader.Name == "Children") {
                                    reader.ReadToDescendant("Children");

                                }
                            }
                        }
                    }
                    break;
            }
        }

But the condition reader.Name == "Children" is never fullfilled... Can someone explain to me why. And maybe show me an easy way to store those values in a List<string> ? Thanks in advance!

EDIT: I edited the xml. Sorry for that but its really hard to filter the unnecassary confusing parts from my xml...

static void GetMostInnerName()
{
    string xml = @"<ProjectConfiguration xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<ProjectLists>   
<ProjectList>
<ListNode>
<Name>Test_Environment</Name>
<Children>
<ListNode>
<Name>yyy</Name>
<Children>
<ListNode>
<Name>205 (ST)</Name>
<Children>
<ListNode>
<Name>098-0031</Name>
<Children />
</ListNode>
<ListNode>
<Name>098-0032</Name>
<Children />
</ListNode>
</Children>
</ListNode>
<ListNode>
<Name>old</Name>
<Children>
    <ListNode>
    <Name>W098-32</Name>
    <Children />
    </ListNode>
</Children>
</ListNode>
</Children>
</ListNode>
<ListNode>
<Name>xxx</Name>
<Children>
<ListNode>
<Name>098-0001</Name>
<Children />
</ListNode>
<ListNode>
<Name>098-0011</Name>
<Children />
</ListNode>
</Children>
</ListNode>
// more List Nodes
</Children>
</ListNode>
</ProjectList></ProjectLists>
</ProjectConfiguration>";
    XElement root = XElement.Parse(xml).Element("ProjectLists");
    //var xmlns = root.GetDefaultNamespace();
    //Console.WriteLine(xmlns);
    var eles = root.Elements("ProjectList").SelectMany(x => x.Elements("ListNode"));
    List<string> list = new List<string>();
    foreach (var ele in eles)
    {
        Loop(ele, list);
    }
    list.ForEach(x =>
    {
        Console.WriteLine(x);
    });
}
static void Loop(XElement ele, List<string> list)
{
    var child = ele.Element("Children");
    if (child != null && child.HasElements)
    {
        foreach (var e in child.Elements("ListNode"))
        {
            Loop(e, list);
        }
    }
    else
    {
        list.Add(ele.Element("Name").Value);
    }
}

Because your xml has many node like ProjectList ,so I used SelectMany here,and I add root element to have a test,the last output is

098-0031
098-0032
W098-32
098-0001
098-0011
private static void FillNames(XElement container, List<string> result)
{
    XElement[] listNodes = container.Elements("ListNode").ToArray();
    if (!listNodes.Any())
        return;

    foreach (XElement listNode in listNodes)
    {
        XElement nameElement = listNode.Element("Name");
        if (nameElement == null)
            continue;

        XElement childrenElement = listNode.Element("Children");
        if (childrenElement == null)
            continue;

        if (!childrenElement.HasElements)
            result.Add(nameElement.Value);
        else
            FillNames(childrenElement, result);
    }
}

static void Main(string[] args)
{
    var result = new List<string>();

    string xml = Resources.Xml; // TODO: put your xml here

    XDocument doc = XDocument.Parse(xml);
    if (doc.Root == null)
        return;

    XElement[] projects = doc.Root.Elements("ProjectList").ToArray();

    foreach (XElement project in projects)
        FillNames(project, result);
}

Can this help?:)

                string path = @"path.xml";

                   if(File.Exists(path)){
                XmlTextReader reader = new XmlTextReader(path);

                Console.WriteLine("");
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {

                        case XmlNodeType.Element:  
                            Console.Write("<" + reader.Name);
                            Console.WriteLine(">");
                            break;

                        case XmlNodeType.Text:   
                            Console.WriteLine(reader.Value);
                            break;
                        case XmlNodeType.EndElement: 
                            Console.Write("</" + reader.Name);
                            Console.WriteLine(">");
                            break;
                    }
                }
                Console.ReadLine();
                   }else{
                       Console.WriteLine("Error file not found");
                   }

What language is this in? You would traverse XML similarly to JSON, by using tags.

Use LinqToXml

var xDocument = XDocument.Parse("yourXmlString");
        XNamespace ns = xDocument.Root.GetDefaultNamespace();
        var result = (from e in xDocument
                          .Descendants(ns + "ListNode").Descendants(ns + "Children")
                          .Descendants(ns + "ListNode").Descendants(ns + "Children")
                          .Descendants(ns + "ListNode").Descendants(ns + "Children")
                          .Descendants(ns + "ListNode")
                           select e.Element(ns + "Name").Value).ToList();

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