[英]How to remove text from XmlNode?
假设我有一个XmlNode:
<A>1</A>
如何从中删除文本,所以我得到:
<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);
}
您是否尝试过将XmlElement.IsEmpty
设置为true?
(显然,这意味着强制转换为XmlElement
,但这是该问题才有意义的唯一情况。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.