我想创建一个 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/