简体   繁体   中英

XmlElement convert open tag to string c#

I need to convert to string a subset of OuterXml content of a XmlElement as in the following example.

Imagine I have an XmlElement object representing the some-element tag

<some-element attribute="value">
    <inner-element>
        text content
    </inner-element>
</some-element>

What's the best approach to get a string that is just <some-element attribute="value"> ?

If possible, I'd prefer a solution without regular expressions involved, but using DOM classes

You can get the full XML of the element(which includes the close tag) by shallow cloning the node and then grabbing the outer XML of the node:

var xml = @"<some-element attribute=""value"">
     <inner-element>
         text content
      </inner-element>
    </some-element>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

MessageBox.Show(doc.DocumentElement.CloneNode(false).OuterXml);

I think after that point you will have to do some string manipulation to get exactly what you want, but that is relatively easy:

var outer = doc.DocumentElement.CloneNode(false).OuterXml;
var final = outer.Substring(0, outer.LastIndexOf(">", outer.Length - 2)+1);

MessageBox.Show(final);

I finally solved it by creating a temporary XElement instead using LINQ

IEnumerable<XAttribute> attributes = (from XmlAttribute xmlAttribute in node.Attributes select new XAttribute(xmlAttribute.Name, xmlAttribute.Value));

var xElement = new XElement(node.Name, attributes);

return xElement.ToString();

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