简体   繁体   English

如何从一个XML元素中删除所有属性?

[英]How do I remove all attributes from one XML element?

I have the following string containing XML: 我有以下包含XML的字符串:

var mystring = "<?xml version="1.0" encoding="UTF-8"?><?adf version="1.0"?>
<adf>
<example url="https://someurl.com/?id=123&amp;hash=6WHnYZwE" 
anotherurl="https://someurl.com/status?id=123;hash=6WHnYZwE" something="Hi">
    <status>new</status>
    <requestdate>2017-11-15T19:45:23-05:00</requestdate>
    <Apples>
        <color>red</color>
        <origin>Washington</make>
    </Apples>
</example>
</adf>";

I want to remove the attributes from the <example> element so that this 我想从<example>元素中删除属性,以便

<example url="https://someurl.com/?id=123&amp;hash=6WHnYZwE" anotherurl="https://someurl.com/status?id=123;hash=6WHnYZwE" something="Hi">

becomes this 变成这个

<example>

I tried using String.Replace to replace the attributes with an empty string, but the attributes aren't always the same. 我尝试使用String.Replace将属性替换为空字符串,但是属性并不总是相同。 Any help is appreciated! 任何帮助表示赞赏!

I'm a little bit rusty with my XML parsing so I'm sure this can be improved. 我对XML解析有点生疏,因此我相信可以改善这一点。

public void DeleteContentsOfExampleElement()
{
    var mystring = @"<?xml version=""1.0"" encoding=""UTF-8""?><?adf 
version=""1.0""?>  
<adf>  
<example url=""https://someurl.com/?id=123&amp;hash=6WHnYZwE"" 
anotherurl=""https://someurl.com/status?id=123;hash=6WHnYZwE"" 
something=""Hi"">
<status>new</status>  
<requestdate>2017-11-15T19:45:23-05:00</requestdate>
<Apples>
    <color>red</color>
    <origin>Washington</origin>
</Apples>
</example>
</adf>";
    var document = new XmlDocument();
    document.LoadXml(mystring);
    var exampleElements = document.GetElementsByTagName("example");
    foreach (XmlNode exampleElement in exampleElements)
    {
        exampleElement.Attributes?.RemoveAll();
    }
}

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

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