0

I have an xml document that uses multiple namespaces:

<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:xlink="http://www.w3.org/1999/xlink" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://schemas.xmlsoap.org/soap/envelope/ http://www.oasis-open.org/committees/ebxml-msg/schema/envelope.xsd">

    <soap:Header xmlns:eb="http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd"
                 xsi:schemaLocation="http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd">

        <eb:MessageHeader eb:id="ID3305713901556098440508VCPEBV11" eb:version="2.0" soap:mustUnderstand="1">
            <eb:Action>Pong</eb:Action>
            ...

This xml uses several namespaces: soap and eb.

If I know the used namespaces in advance I can do something like: as suggested in this SO question:

XNamespace nsSoap = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace nsEb = "http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd";

XDocument xDoc = XDocument.Load(textReader);
XElement xmlRoot = xDoc.Root;

XElement header = xmlRoot.Element(nsSoap + "Header");
XElement messageHeader = header.Element(nsEb + "MessageHeader");
XElement action = messageHeader.Element(nsEb + "Action");

But what if I don't know the location of the namespaces in advance?

I know they are mentioned in the beginning of XElements, so I gathered: can I ask the XElement for the namespaces it knows all about?

And indeed I can ask the Header about its namespace:

var headerNameSpace = header.Name.Namespace;

But then I get the soap namespace. How can I detect that this header defines the eb namespace?

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116

1 Answers1

0

You can ask the XElement: do you know a namespace for "eb"?

XDocument xDoc = XDocument.Load(textReader);
XElement xmlRoot = xDoc.Root;

// I want the XElement that starts with <soap:header ....
// so I'll ask the XmlRoot if it know a namespace with prefix "soap"
var nsSoap = xmlRoot.GetNameSpaceOfPrefix("soap");
XElement header = xmlRoot.Element(nsSoap + "Header");

// I want to read: <eb:MessageHeader ...
var nsEb = header.GetNameSpaceOfPrefix("eb");
XElement messageHeader = header.Element(nsEb + "MessageHeader");
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116