如何替换XML中的标记

时间:2012-09-07 07:15:18

标签: c# html xml tags

我有一个xml标签,如:

<p xmlns="http://www.w3.org/1999/xhtml">Text1<span title="instruction=componentpresentation,componentId=1234,componentTemplateId=1111">CPText2CP</span></p>

如果我必须用

替换标签<span title="instruction=componentpresentation,componentId=1234,componentTemplateId=1111">CPText2CP</span>

<componentpresentation componentID="1234" templateID="1111" dcpID="dcp1111_1234" dcplocation="/wip/data/pub60/dcp/txt/dcp1111_1234.txt">Text2</componentpresentation>

有任何可能的方式来实现这一点,请提出建议/更改。

修改

从上面的标记我可以将完整的<span></span>标记作为字符串,其中的文本位于标记之间。任何建议。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

        string input = @"
            <p xmlns=""http://www.w3.org/1999/xhtml"">
                Text1
                <span title=""instruction=componentpresentation,componentId=1234,componentTemplateId=1111"">
                    CPText2CP
                </span>
            </p>";


        XDocument doc = XDocument.Parse(input);
        XNamespace ns = doc.Root.Name.Namespace;

        // I don't know what filtering criteria you want to use to 
        // identify the element that you wish to replace,
        // I just searched by "componentId=1234" inside title attribute
        XElement elToReplace = doc
            .Root
            .Descendants()
            .FirstOrDefault(el => 
                el.Name == ns + "span" 
                && el.Attribute("title").Value.Contains("componentId=1234"));

        XElement newEl = new XElement(ns + "componentpresentation");

        newEl.SetAttributeValue("componentID", "1234");
        newEl.SetAttributeValue("templateID", "1111");
        newEl.SetAttributeValue("dcpID", "dcp1111_1234");
        newEl.SetAttributeValue("dcplocation", 
            "/wip/data/pub60/dcp/txt/dcp1111_1234.txt");

        elToReplace.ReplaceWith(newEl);

您的需求可能会有所不同,但最重要的方法是创建XDocumentXElement,搜索它以查找需要替换的元素,然后使用ReplaceWith替换它们。请注意,您必须考虑名称空间,否则将无法检索元素。

答案 1 :(得分:1)