1

I need to get the content of the POIssuedDate tag of the below XML using LINQ. Below is the code I wrote that I think should work.

EDIT : Just tried with XNamespace bat = @"x-commerceone:document:btsox:Batch.sox$1.0"; and XNamespace bat = @"urn:x-commerceone:document:btsox:Batch.sox$1.0"; both dont work.

The code throws an exception "Sequence contains no elements" which i expect if nothing matches given im using the First() method

Code

XDocument baseXML = XDocument.Load(Path.Combine(XMLFolder + @"\Provide.xml"));
XNamespace bat = @"xmlns:bat=""urn:x-commerceone:document:btsox:Batch.sox$1.0";

string date = baseXML.Descendants(bat + "Batch").Elements("PurchaseOrder").Elements("OrderHeader").Elements("POIssuedDate").First().Value;

XML

<?soxtype urn:x-commerceone:document:btsox:Batch.sox$1.0?>
<?import urn:x-commerceone:document:telcoapisox:ServiceRequestOrder.sox$1.0?>
<?import urn:x-commerceone:document:com:commerceone:CBL:CBL.sox$1.0?>
<?import urn:x-commerceone:document:btsox:DSL.sox$1.0?>
<bat:Batch BatchID="B-15-6-2001-4" NoOfEntries="3" xmlns="urn:x-commerceone:document:com:commerceone:CBL:CBL.sox$1.0" xmlns:bat="urn:x-commerceone:document:btsox:Batch.sox$1.0" xmlns:sro="urn:x-commerceone:document:telcoapisox:ServiceRequestOrder.sox$1.0" xmlns:dsl="urn:x-commerceone:document:btsox:DSL.sox$1.0">
  <PurchaseOrder>
    <OrderHeader>
      <POIssuedDate>20010615T15:12:03</POIssuedDate>
..SNIP
    </OrderHeader>
  </PurchaseOrder>
</bat:Batch>
Tom Squires
  • 8,848
  • 12
  • 46
  • 72
  • You say the code you "think should work" - does it not? If not, what is wrong with it? – Samuel Slade Dec 21 '11 at 14:35
  • XNamespace bat = @"urn:x-commerceone:document:btsox:Batch.sox$1.0"; http://msdn.microsoft.com/us-en/library/system.xml.linq.xnamespace.aspx – BLUEPIXY Dec 21 '11 at 14:41

2 Answers2

2

The namespace shouldn't include the "xmlns:bat" part:

XNamespace bat = "urn:x-commerceone:document:btsox:Batch.sox$1.0";
XNamespace ns = "urn:x-commerceone:document:com:commerceone:CBL:CBL.sox$1.0";

In addition, you have to specify the namespace for every element:

string date = baseXML.Descendants(bat + "Batch")
                     .Elements(ns + "PurchaseOrder")
                     .Elements(ns + "OrderHeader")
                     .Elements(ns + "POIssuedDate")
                     .First().Value
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
2
XNamespace bat = @"urn:x-commerceone:document:btsox:Batch.sox$1.0";
XNamespace ns  = @"urn:x-commerceone:document:com:commerceone:CBL:CBL.sox$1.0";

string date = baseXML.Descendants(bat + "Batch").Elements(ns + "PurchaseOrder").Elements(ns + "OrderHeader").Elements(ns + "POIssuedDate").First().Value;
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70