2017-08-29 71 views
2

我試圖匹配XML中的Location標記,並將xml內容中的「\」替換爲位置標記中的「\\」,任何人都可以提供有關如何執行此操作的指導?如何僅替換XML中的特定標籤的「」和「\」?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 
using System.Threading.Tasks; 

namespace Matchlocationreplacebackslash 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string pattern = "<Location>(.*?)</Location>"; 
      string xmlcontent = @"<SoftwareProductBuild> 
         <BuildSource>QCA_DEV_POSTCOMMIT</BuildSource> 
         <BuiltBy>wbibot</BuiltBy> 
         <CreatedBy>wbibot</CreatedBy> 
         <Name>BTFM.CHE.2.1.2-00091-QCACHROM-1_NO_VARIANT</Name> 
         <Status>Approved</Status> 
         <BuiltOn>2017-08-28T13:00:04.345Z</BuiltOn> 
         <Tag>BTFM.CHE.2.1.2_BTFM.CHE.2.1.2-00091-QCACHROM-1_2017-08-28T13:00:04.345Z</Tag> 
         <SoftwareImageBuilds> 
          <SoftwareImageBuild> 
           <Type>LA</Type> 
           <Name>BTFM.CHE.2.1.2-00091-QCACHROM-1_NO_VARIANT</Name> 
           <Location>\\snowcone\builds676\INTEGRATION\BTFM.CHE.2.1.2-00091-QCACHROM-1</Location> 
           <Variant>NO_VARIANT</Variant> 
           <LoadType>Direct</LoadType> 
           <Target>NO_VARIANT</Target> 
           <SoftwareImages> 
            <SoftwareImage> 
             <Name>BTFM.CHE.2.1.2</Name> 
             <SoftwareProducts> 
              <SoftwareProduct> 
               <Name>MSM8998.LA.1.9</Name> 
               <BaseMeta>CI_MSM8998.LA.1.9-16991-INT-2</BaseMeta> 
              </SoftwareProduct> 
             </SoftwareProducts> 
            </SoftwareImage> 
           </SoftwareImages> 
          </SoftwareImageBuild> 
         </SoftwareImageBuilds> 
        </SoftwareProductBuild>"; 
      Match match = Regex.Match(xmlcontent, pattern); //Match location 
      //Replace "\" with "\\" in the xml content with the match 
      Console.ReadLine(); 
     } 
    } 
} 
+3

請寫明要求。 _並將「\」替換爲「\」..._它們都是相同的。 – Sach

+0

我認爲這個問題的標題有它,因爲他希望用雙斜線代替單斜槓。我們這裏的文字編輯可能會奇怪地處理這個問題。至於這個問題,這感覺就像是「使用LINQ來遍歷XML並改變你想要的就地」的問題。 –

+0

這是SO編輯器中的一個異常 - 出現了\ \。您需要輸入\\\來獲得\\ – cup

回答

4

你不需要正則表達式。使用XML解析器像Linq2Xml

var xDoc = XDocument.Parse(xmlcontent); 
foreach(var loc in xDoc.Descendants("Location")) 
{ 
    loc.Value = loc.Value.Replace(@"\", @"\\"); 
} 

string newXml = xDoc.ToString(); 

PS:一個好的SO後閱讀。 RegEx match open tags except XHTML self-contained tags

0

您可以使用此代碼:如果您需要

var xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml(xmlcontent); 
var locations = xmlDoc.GetElementsByTagName("Location"); 
foreach (XmlNode location in locations) 
{ 
    var newLocation = location.InnerText.Replace("\\", "\\\\"); 
    location.InnerText = newLocation; 
} 

xmlcontent被更新,然後你可以這樣寫:

xmlcontent = xmlDoc.OuterXml; 
相關問題