TeamWild TeamWild - 1 year ago 63
C# Question

Parse XDocument without having to keep specifying the default namespace

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 would have expected the default namespace to be used for all elements.

Is there a more logical way to achieve my goal?

Sample XML:

<?xml version="1.0" encoding="UTF-8"?>
<ReceiptsBatch xmlns="">

Code to read xml elements I'm after:

XDocument xDoc = XDocument.Load( FileInPath );

XNamespace ns = "";

XElement MessageCheck = xDoc.Element(ns+ "MessageHeader").Element(ns+"MessageCheck");
XElement MessageBody = xDoc.Element("Receipts");

Answer Source

The theory is that the meaning of the document is not affected by the user's choice of namespace prefixes. So long as the data is in the namespace, it doesn't matter whether the author chooses to use the prefix "s", "secrets", "", or the "null" prefix (that is, making it the default namespace). Your application shouldn't care: it's only the URI that matters. That's why your application has to specify the URI.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download