Kevin
Kevin

Reputation: 4848

Determining the element in an XDocument

I have an XML document that I'm trying to parse. Here is what it looks like (just the format here, no data):

 <objectdata>
   <title></title>
     <assignableunit>    
       <other></other>    
       <other></other>    
       <text></text>    
       <name></name>
     </assignableunit>    
 </objectdata>

What I had planned on doing was to loop through the xml document and act on each element. For instance, if the element is <assignableunit> I'd call code to act on that particular element. If the element is <text>, I'd call code to act on that.

var xdoc = XDocument.Load("Items.xml");
foreach (XElement element in xdoc.Descendants("objectdata"))
{   
  //if element is <assignableunit>...
  //if element is <other>...
  //if element is <name>...
  //etc... 
}

I thought maybe using a switch/case to determine the type of element would work, but I can't figure out how to determine the type of element. Can someone offer a point in the right direction? I haven't dealt much at all with XML files.

Upvotes: 2

Views: 53

Answers (2)

TyCobb
TyCobb

Reputation: 9089

Because you're using XElement instead of XmlNode or XmlElement which a lot of tutorials/examples use, you need to use Name property which is a XName object. The non-linq objects have these broken out into separate properties such as Name and LocalName while XElement has this combined using the XName type.

if (element.Name.LocalName == "title")
{
   // Do something with title data
}
else if (element.Name.LocalName == "assignableunit")
{
  // Do something with assignableunit data
  foreach(XElement childElement in element.Descendents())
  {
      if (childElement.Name.LocalName == "other")
      {

      }
      else if (........)
      {
      }
  }
}

Upvotes: 1

luksan
luksan

Reputation: 7767

element.Name.LocalName should get you what you want.

http://msdn.microsoft.com/en-us/library/system.xml.linq.xname.localname(v=vs.110).aspx

Upvotes: 3

Related Questions