简体   繁体   English

XmlElement将打开标记转换为字符串C#

[英]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. 我需要将XmlElement的OuterXml内容的子集转换为字符串,如以下示例所示。

Imagine I have an XmlElement object representing the some-element tag 想象一下,我有一个表示some-element标签的XmlElement对象

<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"> ? 获得只是<some-element attribute="value">的字符串的最佳方法是什么?

If possible, I'd prefer a solution without regular expressions involved, but using DOM classes 如果可能,我宁愿不使用正则表达式但使用DOM类的解决方案

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: 您可以通过浅层克隆节点然后获取节点的外部XML来获取元素的完整XML(包括close标签):

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 我终于通过创建一个临时 XElement而不是使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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