1

私は次のような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>の間にテキストを含む文字列として完全なタグを取得できます。任意の提案。

4

2 に答える 2

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から、それらを置き換えるために使用する方法があります。名前空間を考慮する必要があることに注意してください。そうしないと、要素が取得されません。

于 2012-09-07T07:43:39.320 に答える
1

はい。

以下をせよ:

  1. ファイルを読み取る(XMLまたはプレーンテキストとして)
  2. タグ/シーケンスまたはそのサブストリングを検索します
  3. シーケンスを新しいものに置き換えます
于 2012-09-07T07:21:52.477 に答える