I have some XML data (similar to the sample below) and I want to read the values in code.
Why am I forced to specify the default namespace to access each element? I woul
Note that the element Receipts
is also in namespace http://www.secretsonline.gov.uk/secrets
, so the XNamespace
would also be required for the access to the element:
XElement MessageBody = xDoc.Element(ns + "Receipts");
As an alternative to using namespaces note that you can use "namespace agnostic" xpath using local-name()
and namespace-uri()
, e.g.
/*[local-name()='SomeElement' and namespace-uri()='somexmlns']
If you omit the namespace-uri
predicate:
/*[local-name()='SomeElement']
Would match ns1:SomeElement
and ns2:SomeElement
etc. IMO I would always prefer XNamespace
where possible, and the use-cases for namespace-agnostic xpath are quite limited, e.g. for parsing of specific elements in documents with unknown schemas (e.g. within a service bus), or best-effort parsing of documents where the namespace can change (e.g. future proofing, where the xmlns
changes to match a new version of the document schema)