2012-09-07 41 views
1

我有這樣一個XML標籤:如何更換標籤的XML

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

如果我有

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

更換標籤<span title="instruction=componentpresentation,componentId=1234,componentTemplateId=1111">CPText2CP</span>任何可能的方式來找到這個,請給出建議/更改。

編輯

從上面的標籤我可以充分<span></span>標籤與在tags.any建議之間的文本字符串。

+0

有兩個問題。首先,是什麼元素需要被轉換爲title =「instruction = ...」屬性的標誌?另外,dcpID/dcplocation屬性來自哪裏? –

+0

@Lunatic,是的,我需要用標記替換完整的標記,並將標記之間的文本保留爲它。 – SDLBeginner

回答

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來替換它們。請注意,您必須考慮名稱空間,否則元素將不會被檢索。