tags:

views:

293

answers:

3

Is it possible to get the open tag from a XmlNode with all attributes, namespace, etc?

eg.

<root xmlns="urn:..." rattr="a">
   <child attr="1">test</child>
</root>

I would like to retrieve the entire opening tag, exactly as retrieved from the original XML document if possible, from the XmlNode and later the closing tag. Both as strings.

Basically XmlNode.OuterXml without the child nodes.

EDIT

To elaborate, XmlNode.OuterXml on a node that was created with the XML above would return the entire XML fragment, including child nodes as a single string.

XmlNode.InnerXml on that same fragment would return the child nodes but not the parent node, again as a single string.

But I need the opening tag for the XML fragment without the children nodes. And without building it using the XmlAttribute array, LocalName, Namespace, etc.

This is C# 3.5

Thanks

+1  A: 

I think the simplest way would be to call XmlNode.CloneNode(false) which (according to the docs) will clone all the attributes but not child nodes. You can then use OuterXml - although that will give you the closing tag as well.

For example:

using System;
using System.Xml;

public class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(@"<root xmlns='urn:xyz' rattr='a'>
           <child attr='1'>test</child></root>");
        XmlElement root = doc.DocumentElement;
        XmlNode clone = root.CloneNode(false);
        Console.WriteLine(clone.OuterXml);
    }
}

Output:

<root xmlns="urn:xyz" rattr="a"></root>

Note that this may not be exactly as per the original XML document, in terms of the ordering of attributes etc. However, it will at least be equivalent.

Jon Skeet
+1  A: 

How about:

 xmlNode.OuterXML.Replace(xmlNode.InnerXML, String.Empty);

Poor man's solution :)

tzup
I think you meant `n.OuterXml.Replace(n.InnerXml, "");`
Robert Rossney
Yeah, sorry, was too early ...
tzup
+1  A: 

Is there some reason you can't simply say:

string s = n.OuterXml.Substring(0, n.OuterXml.IndexOf(">") + 1);
Robert Rossney