How do I remove the CDATA tag of an XElement?

谁说我不能喝 提交于 2020-01-14 03:32:08

问题


I have some code that receives some XML and there is the possibility that a CDATA tag element will be present. A flag is passed into the method that states whether the CDATA tag should be present, if the flag is false, then the CDATA tag should be removed if present, how would I do this without parsing the query.Value?

private static void CDataTagUtility(XmlDocument catalog, XElement newData, bool addCdataTag)
{
    XElement query = newData.Element("Query").Element("CommandText");
    if (addCdataTag)
    {
        XmlCDataSection encapsulatedQuery = catalog.CreateCDataSection(query.Value);
        try
        {
            query.SetValue(encapsulatedQuery.OuterXml);
        }
        catch (ArgumentException exc) { /*Thrown due to CDATA tag already present - ignore*/ }
    }
    else //check for cdata tag - remove if present
    {
        //How do I remove the CDATA encapsulation tag???
    }
}

回答1:


Try this:

static void RemoveCdata(XmlNode root)
{
    foreach (XmlNode n in root.ChildNodes)
    {
        if (n.NodeType == XmlNodeType.CDATA)
            root.RemoveChild(n);
        else if (n.NodeType == XmlNodeType.Element)
            RemoveCdata(n);
    }
}

...

RemoveCdata(query);


来源:https://stackoverflow.com/questions/3570339/how-do-i-remove-the-cdata-tag-of-an-xelement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!