开发者

How do I remove the CDATA tag of an XElement?

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 CDataTagUtili开发者_如何学编程ty(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???
    }
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜