简体   繁体   English

xml中的简单字符串替换

[英]Simple string replace in xml

I have a string that contains a fair bit of XML, it's actually xml that describes a word document(document.xml). 我有一个包含相当一部分XML的字符串,它实际上是描述单词document(document.xml)的xml。 I want to simply replace a part of the string with an empty string effectivally removing it from the string. 我只想用空字符串替换字符串的一部分,从而有效地将其从字符串中删除。 This sounds straight forward but I'm not getting the result I expect. 这听起来很直接,但是我没有得到我期望的结果。

Here is what some of the XML looks like, this is just the first 10 lines: 这是一些XML的样子,这只是前10行:

<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:p w:rsidR="00CB3A3E" w:rsidP="00257CF7" w:rsidRDefault="008C1E91">
        <w:pPr>
            <w:pStyle w:val="Heading-Title" />
        </w:pPr>
        <w:r>
            <w:t>References</w:t>
        </w:r>
    </w:p>
    <w:sdt> 

As I said this is in a string. 正如我所说的那样。 I simply try to replace <w:t>References</w:t> with an empty string. 我只是尝试用空字符串替换<w:t>References</w:t> I am doing it like so: 我这样做是这样的:

//xmlBody is the string that is holding the xml
xmlBody.Replace("<w:t>References</w:t>", " ");

This is not working, the string is unaltered when I do this. 这是行不通的,当我这样做时字符串没有改变。 What am I doing wrong? 我究竟做错了什么? Any advice would be appreciated, thanks much! 任何建议将不胜感激,非常感谢!

xmlBody = xmlBody.Replace("<w:t>References</w:t>", "");

The Replace function doesn't change the source string; Replace函数不会更改源字符串。 it returns a new string with the changes made. 它返回一个包含所做更改的新字符串。 In fact, C# strings cannot be changed. 实际上,C#字符串无法更改。 If you check out the documentation , it says that they're immutable. 如果您查看文档 ,它说它们是不可变的。

In C#, string is not mutable - once created, it cannot be changed. 在C#中,字符串不可更改-一旦创建,就无法更改。 Replace returns a new instance of string. Replace返回一个新的字符串实例。 Therefore, you need to catch its return value: 因此,您需要捕获其返回值:

xmlBody = xmlBody.Replace("<w:t>References</w:t>", " ");

As a sidenote, it is not considered a good practice to parse XML-based strings with regular expressions, because it's too fragile. 附带说明一下,用正则表达式解析基于XML的字符串不是一个好习惯,因为它太脆弱了。 Consider using XDocument or some such to remove elements you are after. 考虑使用XDocument或类似的工具来删除您想要的元素。

string.replace returns a new string, it doesn't change the original string string.replace返回一个新字符串,它不会更改原始字符串

try 尝试

xmlBody = xmlBody.Replace("<w:t>References</w:t>", " ");

Replace不是内联替换...它会返回已完成替换的新字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM