Reputation: 6839
This is xml that I receive:
<?xml version="1.0" encoding="UTF-8"?>
<mdpr:Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mdpr="http://...">
<mdpr:contactList>
<mdpr:contact ID="{123456}" classID="Customer">
<mdpr:Name>data1</mdpr:Name>
<mdpr:TransportCode>data2</mdpr:TransportCode>
<mdpr:ZipCode>data3</mdpr:ZipCode>
<mdpr:City>data4</mdpr:City>
</mdpr:contact>
<mdpr:contact ID="{234567}" classID="Customer">
<mdpr:Name>data5</mdpr:Name>
<mdpr:TransportCode>data6</mdpr:TransportCode>
<mdpr:ZipCode>data7</mdpr:ZipCode>
<mdpr:City>data8</mdpr:City>
</mdpr:contact>
</mdpr:contactList>
...
Here is how I try to get all contacts:
public class Contact
{
public string Name { get; set; }
public string TransportCode { get; set; }
}
...
XDocument xdoc = XDocument.Load(doc.CreateNavigator().ReadSubtree());
List<Contact> contacts = (from xml in xdoc.Elements("contactList").Elements("contact")
select new Contact
{
Name = xml.Element("Name").Value,
TransportCode = xml.Element("TransportCode").Value
}).ToList();
But I get nothing. What am I doing wrong here?
Upvotes: 1
Views: 76
Reputation: 50752
try to specify namespace
string nmsp = "http://www.w3.org/2001/XMLSchema-instance/"
from xml in xdoc.Elements(nmsp+"contactList").Elements(nmsp + "contact")
Upvotes: 1
Reputation: 63095
XDocument xdoc = XDocument.Load(doc.CreateNavigator().ReadSubtree());
var ns = xdoc.Root.Name.Namespace;
List<Contact> contacts = (from xml in xdoc.Root.Elements(ns +"contactList").Elements(ns +"contact")
select new Contact
{
Name = xml.Element(ns +"Name").Value,
TransportCode = xml.Element(ns +"TransportCode").Value
}).ToList();
Upvotes: 1
Reputation: 236268
You have mdpr
namespace declared in your xml:
xmlns:mdpr="http://..."
but you are providing only local name of elements in query. E.g. you provide contactList
name, but full name of element is mdpr:contactList
. That's why nothing is found.
You should define XNamespace
for your namespace and use it to create full names of elements:
XNamespace mdpr = "http://...";
var contacts = from c in xdoc.Root.Element(mdpr + "contactList")
.Elements(mdpr + "contact")
select new Contact {
TransportCode = (string)c.Element(mdpr + "TransportCode"),
Name = (string)c.Element(mdpr + "Name")
};
Also contactList
is not the root of document. You should search it under Root
.
Upvotes: 1