C# 如何从XmlNode中删除文本?
比如说,我有一个XmlNode:C# 如何从XmlNode中删除文本?,c#,xml,C#,Xml,比如说,我有一个XmlNode: <A>1</A> 1 如何从中删除文本,因此我得到: <A /> 而不是: <A></A> 下面是一个单元测试,它显示了我到目前为止所做的尝试 [Test] public void RemoveXmlTextTest() { string xmlString = @"<B><A>1</A></B>";
<A>1</A>
1
如何从中删除文本,因此我得到:
<A />
而不是:
<A></A>
下面是一个单元测试,它显示了我到目前为止所做的尝试
[Test]
public void RemoveXmlTextTest()
{
string xmlString = @"<B><A>1</A></B>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNode testNode = doc.SelectSingleNode("//A");
//1. Set innerText to string.Empty - not working
//testNode.InnerText = String.Empty;
//2. Call removeAll - not working
//testNode.RemoveAll();
//3. testNode has one child with name '#text' - remove it - not working
//testNode.RemoveChild(testNode.FirstChild);
//4. Replace node with a new empty one - working but extremally ugly :(
//All references to testNode still points to the old one !!!!
testNode.ParentNode.ReplaceChild(doc.CreateElement(testNode.Name), testNode);
//Is there some better way to do it?
testNode = doc.SelectSingleNode("//A");
Assert.AreEqual("<A />", testNode.OuterXml);
}
[测试]
public void RemoveXmlTextTest()
{
字符串xmlString=@“1”;
XmlDocument doc=新的XmlDocument();
doc.LoadXml(xmlString);
XmlNode testNode=doc.SelectSingleNode(“//A”);
//1.将innerText设置为string.Empty-不工作
//testNode.InnerText=String.Empty;
//2.呼叫removeAll-不工作
//testNode.RemoveAll();
//3.testNode有一个子节点名为“#text”-删除它-不工作
//RemoveChild(testNode.FirstChild);
//4.将节点替换为新的空节点-工作正常但非常难看:(
//对testNode的所有引用仍然指向旧的引用!!!!
testNode.ParentNode.ReplaceChild(doc.CreateElement(testNode.Name),testNode);
//有更好的方法吗?
testNode=doc.SelectSingleNode(“//A”);
AreEqual(“,testNode.OuterXml);
}
您是否尝试设置为true
(显然,这意味着转换为XmlElement
,但这是问题唯一有意义的情况。)