简体   繁体   中英

Convert XmlDocument object into an XmlNode object - C#?

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.

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.

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

XmlDocument doc = ...

XmlNode node = doc as XmlNode;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM