2015-01-01 43 views
0

我有一个字符串,它看起来像这样:在一个XML字符串替换字符串

newNodeXML = "<item id="qDf73w8emTg" parent_id="weLPzE243de" type="suite"> 
       <content> 
        <name>Three</name> 
       </content> 
       </item>" 

在我的[的WebMethod],我试图取代PARENT_ID(在运行时随机生成的)像此:

Regex myRegex = new Regex(@""" parent_id=""(.*?)"" type="""); 
newNodeXML = myRegex.Replace(newNodeXML, "d43df2qT45"); 

请注意,例如/演示缘故,我已经在第二行中使用“d43df2qT45”的上方。我实际上也会随机生成它。

我的问题这里是这样的结果。 我不想这样的:

<item id="qDf73w8emTgd43df2qT45suite"> 
    <content> 
     <name>Three</name> 
    </content> 
</item> 

相反,这正是我想要是:

<item id="qDf73w8emTg" parent_ID="d43df2qT45" type="suite"> 
    <content> 
     <name>Three</name> 
    </content> 
</item> 

附:我已经尝试过一些例子/谷歌搜索,我所能找到的所有例子都让我感觉如此。

+3

正则表达式可能是这样做的错误方式。检查出http://stackoverflow.com/questions/2424613/xml-changing-the-value-of-an-attribute – nullforce

+0

“parent_id”值的长度是否固定并且在前面已知? –

+0

为什么你不反序列化这个内容,改变你所需要的,然后再次序列化它? – Crasher

回答

-1

您可以使用括号之前和值后,搭上了一部分,然后使用$1$2,包括他们在更换:

Regex myRegex = new Regex(@"(parent_id="")[^""]+("")"); 
newNodeXML = myRegex.Replace(newNodeXML, "$1" + "d43df2qT45" + "$2"); 

您也可以只使用字符串操作它:

int pos1 = newNodeXML.IndexOf(" parent_id=\"") + 12; 
int pos2 = newNodeXML.IndexOf('"', pos1); 
newNodeXML = newNodeXML.Substring(0, pos1) + "d43df2qT45" + newNodeXML.Substring(pos2); 
6

如果你有一个已知的XML结构,使用XML工具可能比使用refex更好,也更快。例如:

var doc = XDocument.Parse(newNodeXML); 
doc.Root.Attribute("parent_id").Value = "xyz"; 

此代码依赖于您提供的确切结构。所以只有一个item,它是XML文件的根,它有一个名为parent_id的属性。

关于MSDN上的XDocument类型的更多信息。

+0

实际上,使用正则表达式的速度是XML解析字符串速度的两倍。 – Guffa

+0

@Guffa我还没有测试过,你可能是适合这种特殊场景的。但从我的经验来看,XML对于大文档的表现要好于正则表达式。但速度不是我不会去正则表达式的唯一原因。可读性是另一个。此外,我总是试图建议OP可能不知道的解决方案,以便向他学习新的东西:) –

0

由于您对所有内容进行了硬编码,因此实际上不需要使用捕获组。
只是延长了更换,以这样的:

"\" parent_id=\"" + "d43df2qT45" + "\" type=\"" 
0

你可以用这个试试,我测试,它似乎工作:

String newXml = Regex.Replace(xml, "parent_id=\".+\" ", "parent_id=\"" + newID + "\" "); 

下面是一个简单的方法来测试它:

String xml = "<item id=\"qDf73w8emTg\" parent_id=\"weLPzE243de\" type=\"suite\">\n\t<content>\n\t\t<name>Three</name>\n\t</content>\n</item>"; 
String newID = "This is the new parent_Id"; 
Console.WriteLine("Old xml: \n\n" + xml + "\n\n\nNew xml:\n"); 
String newXml = Regex.Replace(xml, "parent_id=\".+\" ", "parent_id=\"" + newID + "\" "); 
Console.WriteLine(newXml); 
Console.ReadKey(); 

只需将其粘贴到控制台应用程序的主要方法中,并包含RegularExpression库:)

0

你可以使用正则表达式来处理你想要做的事情,用像下面这样的正则表达式。

Regex myRegex = new Regex("parent_id=\"([^""]+)\"); 
string myXml = "<myxml>data</myxml>"; 
xdoc.LoadXml(myXml);