Sonamor Sonamor - 3 months ago 12
C# Question

Issue with Namespace on XML Parsing c#

I am trying to read the following XML with C#

<GetAssetWarrantyResponse xmlns="http://tempuri.org/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<GetAssetWarrantyResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset">
<a:Faults />
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true" />
<a:CountryLookupCode>XXXX</a:CountryLookupCode>
<a:CustomerNumber>XXXXXX</a:CustomerNumber>
<a:IsDuplicate>false</a:IsDuplicate>
<a:ItemClassCode>XXX</a:ItemClassCode>
<a:LocalChannel>XXXX</a:LocalChannel>
<a:MachineDescription>XXXXXXX</a:MachineDescription>
<a:OrderNumber>XXXXXX</a:OrderNumber>
<a:ParentServiceTag i:nil="true" />
<a:ServiceTag>XXXXXX</a:ServiceTag>
<a:ShipDate>2010-04-12T19:00:00</a:ShipDate>
<a:Warranties>
<a:Warranty>
<a:EndDate>2011-04-13T18:59:59</a:EndDate>
<a:EntitlementType>INITIAL</a:EntitlementType>
<a:ItemNumber>709-10398</a:ItemNumber>
<a:ServiceLevelCode>CB</a:ServiceLevelCode>
<a:ServiceLevelDescription>Collect and Return Initial with Dates</a:ServiceLevelDescription>
<a:ServiceLevelGroup>5</a:ServiceLevelGroup>
<a:ServiceProvider i:nil="true" />
<a:StartDate>2010-04-12T19:00:00</a:StartDate>
</a:Warranty>
</a:Warranties>
</a:DellAsset>
</a:Response>
</GetAssetWarrantyResult>
</GetAssetWarrantyResponse>


I think I have an issue with the namespace and whatever I've tried so far didn't work.

I've tried so far

XNamespace aw = "a"
XNamespace aw = "a:"
XNamespace aw = "http://schemas.xmlsoap.org/soap/envelope/"


and some other than I can't recall at the moment

private void btDellWaranty_Click(object sender, EventArgs e)
{
string serviceTag = tbDellServiceTag.Text;
string uri= https://api.dell.com/support/v2/assetinfo/warranty/tags?svctags=XXXX&apikey=XXXX";
XDocument Doc = XDocument.Load(uri);
XNamespace aw = "a";
string result = doc.from u in Doc.Descendants(aw + "DellAsset") select (string)u.Element(aw + "MachineDescription").Value;

XElement result = Doc.Root.Element("GetAssetWarrantyResponse");

}


Any ideas?

Notes: I pass the
tbDellServiceTag.Text
correctly to the
uri
so that's not the issue.

Answer

The namespace for a prefix (e.g. a:DellAsset has the prefix a) is denoted by the xmlns:a="..." of the element or the first ancestor element that contains that namespace declaration - GetAssetWarrantyResult in this case.

So, your namespace is:

XNamespace aw = "http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset"