0

can anyone tell me why, given the following XDocument contents

<AddOrderResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <ErrorMessage xmlns="http://schemas.datacontract.org/2004/07/appulsive.Intertek.LIMSService">, Fehler in der Belegerfassung Verkauf
Die Kontokorrentdaten konnten nicht gelesen werden.
(Exception of type 'Sagede.OfficeLine.Wawi.BelegEngine.RecordsetEmptyException' was thrown.)</ErrorMessage>
</AddOrderResult>

and the following C# code

    var resultElement =xmlResponse.Element("AddOrderResult");
    var errorMessage = resultElement.Element("ErrorMessage");

where xmlResponse is the XDocument object in question, resultElement is a valid XElement but errorMessage is always null? Is it, for example, something to do with the ErrorMessage namespace?

TIA.

2
  • Can you show how you are parsing the XML? Commented May 27, 2015 at 16:06
  • XDocument.Parse(theXMLString); Commented May 28, 2015 at 12:27

1 Answer 1

3

You're missing the namespace for ErrorMessage - it's different than the root XMLNS, and needs to be specified. This code will get your element correctly:

string rawXmlString = @"<AddOrderResult xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
  <ErrorMessage xmlns=""http://schemas.datacontract.org/2004/07/appulsive.Intertek.LIMSService"">, Fehler in der Belegerfassung Verkauf
Die Kontokorrentdaten konnten nicht gelesen werden.
(Exception of type 'Sagede.OfficeLine.Wawi.BelegEngine.RecordsetEmptyException' was thrown.)
  </ErrorMessage>
</AddOrderResult>";

XDocument xmlResponse = XDocument.Parse(rawXmlString);

var resultElement =xmlResponse.Element("AddOrderResult");
XNamespace ns = "http://schemas.datacontract.org/2004/07/appulsive.Intertek.LIMSService";
var errorMessage = resultElement.Element(ns + "ErrorMessage");

You could also get it without the namespace, but it's a bit more clunky...

var errorMessage_NoNS = resultElement.Elements().Where(x => x.Name.LocalName == "ErrorMessage").FirstOrDefault();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - I'll try that approach. I wondered if the different namespace was culpable.
The non-clunky approach, I meant. Solved the problem at a stroke. Thanks.
Glad to hear - the clunky approach was added later as an afterthought, in case you have to deal with this a lot and don't always know the namespace ahead of time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.