Heres my XML
<metadata created="2015-02-24T17:50:40.188Z" xmlns="http://example.com" xmlns:ext="http://example.com">
<customer-group-list count="10">
<customer-group id="790174c22752" type="Corporate">
<title>Mr</title>
<primary-type>Corporate</primary-type>
<customer-credit>
<name-credit>
<customer id="3d57f91ecf5e">
<name>Michael Jackson</name>
<sort-name>Jackson, Michael</sort-name>
<alias-list>
<alias sort-name="JACKSON MICHAEL JOE">JACKSON MICHAEL JOE</alias>
</alias-list>
</customer>
</name-credit>
</customer-credit>
</customer-group>
</customer-group-list>
</metadata>
Im trying to get the (Customer ID), So i have this code
XDoc = XDocument.Parse(XDoc.ToString());
GetCustomers = from c in XDoc.Descendants(ns + "customer-group")
select
new Customer
{
ID = c.Element(ns + "customer-credit").Elements(ns + "name-credit").Any()
? c.Element(ns + "customer").Attribute(ns + "id").Value
: "",
Title = c.Element(ns + "title").Value,
};
So the ID line of code is where im attempting to nest into the node i need and then get the ID but i get "Object not set to an instance" error and not sure if theres a way to do this or not?
I thought i understood this but if you are posting an answer i would appreciate any explanation of how to get to nested Elements in this fashion.
Thanks
The problem in your code is in the ID line
? c.Element(ns + "customer").Attributes(ns + "id").Value
You can not just jump to an inner element like that. if you want the query to work you can use
? c.Descendants(ns + "customer").Attributes("id").Value
If you can figure out a solution with the hint. This is the full code
void static Main()
{
var xml= @"<metadata created=""2015-02-24T17:50:40.188Z"" xmlns=""http://example.com"" xmlns:ext=""http://example.com"">
<customer-group-list count=""10"">
<customer-group id=""790174c22752"" type=""Corporate"">
<title>Mr</title>
<primary-type>Corporate</primary-type>
<customer-credit>
<name-credit>
<customer id=""3d57f91ecf5e"">
<name>Michael Jackson</name>
<sort-name>Jackson, Michael</sort-name>
<alias-list>
<alias sort-name=""JACKSON MICHAEL JOE"">JACKSON MICHAEL JOE</alias>
</alias-list>
</customer>
</name-credit>
</customer-credit>
</customer-group>
</customer-group-list>
</metadata>";
XNamespace nameSpace = "http://example.com";
XElement dataSet1Tree = XElement.Parse(xml);
var dataSet1List = from cg in dataSet1Tree.Descendants(nameSpace +"customer-group")
let customer = cg.Descendants(nameSpace +"customer").FirstOrDefault()
let title = cg.Descendants(nameSpace +"title").FirstOrDefault()
select new {
ID = customer == null ? "" : customer.Attributes("id").First().Value,
Title = title == null? null : title.Value
};
foreach(var cust in dataSet1List)
{
Console.WriteLine(cust.ID +" " + cust.Title);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.