我正在尝试匹配XML中的Location
标记并替换" \"用" \\"在仅适用于Location标记的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();
}
}
}
答案 0 :(得分:4)
您不需要正则表达式。使用像Linq2Xml
这样的xml解析器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
答案 1 :(得分: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;