我想找到包含某个字符串的元素属性的所有实例并进行更改。
示例xml将是:
<system>
<template>
<url address="http://localhost:7888/Application/basic" />
<url address="http://localhost:7997/sdk/basic" />
<url address="http://localhost:5855/htm/ws" />
<url address="net.tcp://localhost:5256/htm" />
<url address="http://localhost:5215/htm/basic" />
<url address="http://localhost:5235/htm/ws" />
<url address="net.tcp://localhost:5256/htm" />
<url address="http://localhost:5252/Projectappmgr/basic"/>
<url address="http://localhost:5295/Projectappmgr/ws" />
</template>
</system>
我有以下代码:
XmlNodeList nodelist = doc.GetElementsByTagName("url");
foreach (XmlNode node in nodelist)
{
if (node.Attributes["address"].Value.Contains("localhost"))
{
string origValue = node.Attributes["address"].Value;
string modValue = String.Empty;
Console.WriteLine("Value of original address is: " + origValue);
modValue = origValue.Replace("localhost", "newURLName");
Console.WriteLine("Value of modified address is: " + modValue);
node.Attributes["address"].InnerText = modValue;
}
}
这会按预期修改地址'值。
<url address="http://newURLName:7888/Application/basic" />
但是,我真正想要的是用newURLName
替换整个字符串“localhost:7888”。有没有办法将端口号指定为通配符,因为它们不会与示例xml块中的相同?
我知道我需要将替换值设置为“localhost:xxxx”,但是“xxxx”在每个实例中都是不同的,我现在正在绘制一个空白。
由于
答案 0 :(得分:2)
正则表达式应该有帮助:
modValue = Regex.Replace(url, @"localhost(:\d+){0,1}", newUrlName)
答案 1 :(得分:2)
您可以使用xpath查找包含搜索字符串的节点,然后使用UriBuilder
类修改您的网址:
var xdoc = XDocument.Parse(xml);
var nodes = xdoc.XPathSelectElements("//url[contains(@address, 'localhost')]");
foreach (var node in nodes)
{
var ub = new UriBuilder(node.Attribute("address").Value);
ub.Host = "newURLName";
node.SetAttributeValue("address", ub.ToString());
}
这会让你
<system>
<template>
<url address="http://newURLName:7888/Application/basic" />
<url address="http://newURLName:7997/sdk/basic" />
<url address="http://newURLName:5855/htm/ws" />
<url address="net.tcp://newURLName:5256/htm" />
<url address="http://newURLName:5215/htm/basic" />
<url address="http://newURLName:5235/htm/ws" />
<url address="net.tcp://newURLName:5256/htm" />
<url address="http://newURLName:5252/Projectappmgr/basic" />
<url address="http://newURLName:5295/Projectappmgr/ws" />
</template>
</system>
来自您的XML示例,即使没有using of regex。
答案 2 :(得分:0)
替换
modValue = origValue.Replace("localhost", "newURLName");
通过
modValue = Regex.Replace(origValue, "localhost(:[0-9]+){0,1}", "newURLName");
答案 3 :(得分:0)
正则表达式的替代方法是使用强类型Uri对象和UriBuilder。
var origValue = new Uri(node.Attributes["address"].Value);
var uriBuilder = new UriBuilder(origValue);
uriBuilder.Host = newHost;
uriBuilder.Port = newPort;
modValue = uriBuilder.Uri;
这可能看起来很长,但它是一个简单的正则表达式的替代品,给你一些强类型的东西,并允许你验证Uri实际上是有效的(参见Uri类方法/属性)。您也可以一步完成主机和端口号,我还没有玩过。