Question

I have an xml as below

<xml>
<action OptAttr ="true">somevalue1</action>
<action>somevalue2</action>
<action OptAttr ="true">somevalue3</action>
</xml>

OptAttribute is an optional attribute which may not be present in all nodes. I want to retrive both OptAttr(if present) and somevalue1,2 etc.

Best way to do using xmldocument/xmlreader?

thanks, Adarsh

Was it helpful?

Solution

If Linq to Xml is available to you, then I recommend to use it

var xdoc = XDocument.Load(path_to_xml);
var actions = from a in xdoc.Root.Elements("action")
              select new {
                  Value = (string)a,
                  OptAttr = (bool?)a.Attribute("OptAttr")
              };

This query parses actions into following anonymous objects:

[
  { Value: "somevalue1",  OptAttr: true },
  { Value: "somevalue2",  OptAttr: null },
  { Value: "somevalue3",  OptAttr: true }
]

If you want to use default value(e.g. false) for OptAttr instead of nullable boolean, then you can provide it with null-coalescing operator

OptAttr = (bool?)a.Attribute("OptAttr") ?? false

UPDATE: Parsing actions into list of ObjectA:

List<ObjectA> actions = (from a in xdoc.Root.Elements("action")
                         select new ObjectA {
                            Value = (string)a,
                            OptAttr = (bool?)a.Attribute("OptAttr")
                         }).ToList();

Or lambda syntax (I don't like to mix it with query syntax)

var actions = xdoc.Root.Elements("action")
                  .Select(a => new ObjectA {
                       Value = (string)a,
                       OptAttr = (bool?)a.Attribute("OptAttr")
                   }).ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top