c# - 创建一个没有属性和第一个元素的 XmlDocument

标签 c# xml xmldocument

我想创建一个 XmlDocument 对象,忽略第一行,并删除所有其他元素的所有属性。 我该怎么做?我拥有的xml字符串和代码如下所示。

<?xml version="1.0" encoding="utf-8"?>
<boolean xmlns="http://tempuri.org/">true</boolean>

我使用的 C# 代码是:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);//xmlString is the value in snippet above this

最佳答案

我从this SO question得出这个解决方案。这是一个完整的工作 MSTest 类。

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var xmlString = @"<?xml version=""1.0"" encoding=""utf-8""?>
                            <root>
                                <boolean xmlns=""http://tempuri.org"" atr=""test"">true</boolean>
                                <boolean xmlns=""http://tempuri.org"" atr=""test"">true</boolean>
                                <boolean xmlns=""http://tempuri.org"" atr=""test"">true</boolean>
                                <boolean xmlns=""http://tempuri.org"" atr=""test"">true</boolean>
                            </root>";
        var xElement = XElement.Parse(xmlString);


        var expectedXmlString = @"<root>
                                <boolean>true</boolean>
                                <boolean>true</boolean>
                                <boolean>true</boolean>
                                <boolean>true</boolean>
                            </root>";
        var expectedXElement = XElement.Parse(expectedXmlString);

        var actualXElement = stripAttributes(xElement);

        Assert.AreEqual(expectedXElement.ToString(), actualXElement.ToString());
    }

    static XElement stripAttributes(XElement root)
    {
        return new XElement(
            root.Name.LocalName,
            root.HasElements ?
                root.Elements().Select(el => stripAttributes(el)) :
                (object)root.Value
        );
    }
}

关于c# - 创建一个没有属性和第一个元素的 XmlDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21223716/

相关文章:

C# - 确定参数是否已传递失败的方法

c# - xmldocument 和嵌套模式

C# 9.0 记录 - 不可为空的引用类型和构造函数

android - 为按钮定义 xml 文件以根据状态更改背景和文本颜色

java - Jersey 将我的 mysql 时间戳写为 2011-09-28T21 :48:25Z how do I format it in Java?

xml - 具有简单和嵌套标签的 xml 的 clj-xpath

c# - 在 C# 中使用 XPath 表达式读取 XML 文件

c# - 如何从 XmlDocument 中选择具有 XML 命名空间的 XML 节点?

c# - C# 中 'try' 的性能成本

c# - LINQ WhereClause 的问题