1

I'm a novice w/ the Linq parsing in .NET. I have probably a simple question that I'm hoping someone can quickly answer for me. I have a huge xml that I've condensed down to figure out why my query fails. I need to parse an element from the xml that's within an node containing an attribute type. The query needs to match the attribute type and return the element value for the element name. However, the problem I'm having is, my xml has d: prefixes before the attribute name and element name and my Linq query just chokes on it. If I remove the d: prefix from the xml and query string, it works and returns the correct values, but with prefixes it doesn't work. Can someone look at my Linq query and see what I'm doing wrong with the prefixes?

Condensed xml code

<root>
  <Contact xmlns:c="http://test/common/1.0">
    <c:IBase type="d:testInfo" xmlns:d="http://">
      <d:ActivityID>00000</d:ActivityID>
    </c:IBase>
    <c:IBase type="d:testInfo" xmlns:d="http://">
      <d:ActivityID>00001</d:ActivityID>
    </c:IBase>
  </Contact>
</root>

Linq Query

var node = from el in xml.Descendants("IBase")
where 
    el.Attribute("type").Value == "testInfo"
select el.Element("ActivityID").Value;

foreach ( String s in node )
  Console.WriteLine(string.Format("Id= {0}",s));

1 Answers1

1

You have two problems to address here.

  1. You need to specify the namespace as part of the query, as Bradley Uffner mentioned in his comment.
  2. The type actually has a "d:" in it, which is not a namespace since it is in the value of the attribute, so you need to compare against "d:testInfo" and not just "testInfo"

Try the following:

XDocument xml = XDocument.Parse(myXmlString);
XNamespace xnc = "http://test/common/1.0";
XNamespace xnd = "http://";
var node = from el in xml.Descendants(xnc + "IBase")
where 
    el.Attribute("type").Value == "d:testInfo"
select el.Element(xnd + "ActivityID").Value;

foreach ( String s in node )
  Console.WriteLine(string.Format("Id= {0}",s));
MatthewG
  • 8,583
  • 2
  • 25
  • 27