8

How do I convert an XmlDocument to a XmlNode in C#? I need to send the entire XmlDocument object to as an input parameter to a .NET web service.

2
  • A complex type defined in the .NET Framework seems like a poor choice for a parameter to a Web Service. If the service is yours, you might look into changing the type to string. That would also let you call it from other languages/platforms with relative ease. Commented Mar 5, 2010 at 2:26
  • @TrueWill - The service is not mine, it is a third paty vendor serivce. Commented Mar 5, 2010 at 11:54

3 Answers 3

10

A XmlDocument is a XmlNode, so you can just pass the document object.

Or you could send its DocumentElement, or any Node returned from an XPath query.

XmlDocument doc = null;
XmlNode node = doc;

XmlNode node = doc.DocumentElement;

XmlNode node = doc.SelectSingleNode("/foo/bar");

No casting or converting is needed unless you need to disambiguate XmlNode from XmlDocument for a method with overloads for both parameter types. If this is the case, use either of the cast or as operators.

Sign up to request clarification or add additional context in comments.

Comments

3

If you need to refer to it explicitly as an XmlNode use "as":

XmlDocument doc = ...

XmlNode node = doc as XmlNode;

Comments

0

An XmlDocument is derived from XmlNode, but you could also send the XmlDocument.DocumentElement which is an XmlElement but ultimately derived from XmlNode. You might need to check in XmlDocument.DocumentElement == null.

Comments

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.