2009-04-16 8 views
0

Disons que j'ai un XmlNode:Comment supprimer du texte de XmlNode?

<A>1</A> 

Comment retirer un texte, donc je reçois:

<A /> 

au lieu de:

<A></A> 

Ci-dessous est un test unitaire qui montre ce que j'ai essayé jusqu'à présent.

[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); 
    } 

Répondre

2

Avez-vous essayé de définir XmlElement.IsEmpty à true?

(Évidemment ceci signifie mouler à XmlElement, mais c'est la seule situation dans laquelle la question a un sens.)

Questions connexes