【问题标题】:How to replace the tags in a XML如何替换 XML 中的标签
【发布时间】:2012-09-01 01:32:26
【问题描述】:

我有一个 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>标签作为一个字符串,标签之间有文本。任何建议。

【问题讨论】:

  • 两个问题。首先,需要转换哪些元素的标志是 title="instruction=..." 属性吗?另外,dcpID/dcplocation 属性从何而来?
  • @Lunatic ,是的,我需要用 标签替换完整的 标签,保持标签之间的文本为 itis。

标签: c# html xml tags


【解决方案1】:

你可以这样做:

        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 替换它们。请注意,您必须考虑命名空间,否则将无法检索元素。

【讨论】:

    【解决方案2】:

    是的。

    执行以下操作:

    1. Read the File(作为 XML 或 plain Text
    2. 搜索the Tag/Sequence or a substring of it
    3. Replace the Sequence with the new one

    【讨论】:

      猜你喜欢
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 2015-10-15
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多