简体   繁体   中英

C# Read XML Hierarchy and use FailOver from the parent

I want to create the following XML.
many kids inside one parent, parent contains kid related nodes (as default for the kids), if the kid is missing a node, the parent will be the failover and give the kis its default node.

<parents>
   <parent>
      <!--all parent related nodes will be here-->

      <kid-prop>default kid prop</kid-prop><!--this is the default for all kids-->
      <kids>
         <kid>
            <kid-prop>some data</kid-prop>
         </kid>
         <kid></kid><!--since this kid does not have have <kid-prop>, it will be taken from the parent-->
      <kids>
   <parent>
<parents>

How to do it programatically it is a no-brainer, the question is , is there any annotation way to tell the xmlreader that the parent is the failover of the kids, in case the kid is missing something

No - XmlReader will read you XML as is, there's no concept of "annotations". If you were using System.Xml.Linq and not XmlReader, it'd be pretty easy:

var defaultValue = (string)root.Element("parent").Element("kid-prop");
root.Element("parent").Element("kids")
.Elements("kid")
.Select(kid => 
       kid.Elements("kid-prop").Any() ? 
       (string)kid.Element("kid-prop") : defaultValue);

By Using XmlReader you can solve the requirement but it needs lot of checks

Below is the sample code

     using (XmlReader reader = XmlReader.Create(@"D:\Sample.xml"))
        {

            bool b = false;
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {

                    if (reader.Name == "parent")
                    {
                        b = true;
                    }

                    if (reader.Name == "kid")
                        b = false;

                    if (!b && reader.Name == "kid-prop")
                    {
                        Console.WriteLine(reader.ReadElementContentAsString());
                    }

                    if (b && reader.Name == "kid-prop")
                    {
                        Console.WriteLine(reader.ReadElementContentAsString());
                    }
                }
            }
        }

Otherwise it is better to use linq to xml as shown in below

        XElement root = XElement.Load(@"D:\Sample.xml");

        var coll = root.Element("parent").Element("kids").Elements("kid").Select(kid => kid.Elements("kid-prop").Any() ? (string)kid.Element("kid-prop") : (string)root.Element("parent").Element("kid-prop"));

        foreach (var item in coll)
        {
            Console.WriteLine(item);
        }

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