Looping through an XML document and assigning data

2019-09-06 02:16发布

问题:

I have an XML file that has several tags like this:

<sitecollection name="">
  <site name="">
    <maingroup name=""> 
       <group name=""> </group>
    </maingroup> 
   </site>
<sitecollection>

The idea is to loop through all the sitecollection and it's child elements in the XML document, and save the info in variables. The problem I'm having is saving the child elements, with their attributes.

So far I have the following code:

class xmlreader
{
    public static void Main()
    {
        XDocument xdoc = XDocument.Load("xmldocument.xml");
        var result = new System.Text.StringBuilder();
        var lv1s = from lv1 in xdoc.Descendants("sitecollection")
                   select new
                   {
                       siecollection = lv1.Attribute("name").Value,
                       maingroup = lv1.Descendants("group")

                   };
        foreach (var lv1 in lv1s)
        {
            result.AppendLine(lv1.siecollection);
            foreach (var lv2 in lv1.maingroup)
                result.AppendLine("   " + lv2.Attribute("name").Value);
        }

    }
}

回答1:

If the sample XML you provided is accurate, the problem is likely that you don't have a closing tag for sitecollection.

I tried your code with a slightly varied XML input (closed the sitecollection tag, and added some values to the name attributes so there would be something to collect in the result StringBuilder) as follows:

XDocument xdoc = XDocument.Parse(@"<sitecollection name=""collectionName"">
    <site name=""sitename"">
    <maingroup name=""maingroupname""> 
    <group name=""groupname""> </group>
    </maingroup> 
    </site>
    </sitecollection>
    ");

and result.ToString() produces: "collectionName\r\n groupname\r\n"



回答2:

Take this where you will:

  XmlReader reader = XmlReader.Create(@"C:\file.xml", null);
  StringBuilder result = new StringBuilder();
  while (reader.Read())
  {            
      if( reader.NodeType == XmlNodeType.Element)
      {
          if (reader.HasAttributes) 
          {
              result.AppendLine(reader.LocalName);
              reader.MoveToFirstAttribute();
              result.AppendLine("  " + reader.Value);                    
          }
       }                      
    }