Friday, November 19, 2010

Linq to XML for those XML Files which has namespace in it

For example I have a XML file myfile.xml

< ?xml version="1.0" encoding="utf-8"?>

< Products xmlns="http://mytest.xsd">
< Product id="1">
< name> myProduct < /name>
< /Product>
< /Products>

eg. in xsd file we know id is interger.
When we use Linq to XML to query this file, when dealing with XElement or XDecendents, the parameter should be Namespace+ElementName, The code is like below:

XNamespace myNS = XNamespace.Get("http://mytest.xsd");
XDocument myDoc = XDocument.Load(@"myfile.xml");
var query = from c in myDoc.Descendants(myNS + "product")
select new
{MyID=c.Attribute("id")!=null?c.Attribute("id").ToString():String.Empty,
MyName=c.Element(myNS+"name")!=null?MyName=c.Element(myNS+"name").ToString():String.Empty}

No comments: