替换XML文件中的值

本文关键字:文件 XML 替换 | 更新日期: 2023-09-27 18:01:45

应用程序需要处理XML文件。有时我们会收到值如下的xml:

<DiagnosisStatement>
     <StmtText>ST &</StmtText>
</DiagnosisStatement>

由于&<,我的应用程序无法正确加载XML并抛出异常,如下所示:

An error occurred while parsing EntityName. Line 92, position 24.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
   at System.Xml.XmlTextReaderImpl.Throw(String res)
   at System.Xml.XmlTextReaderImpl.ParseEntityName()
   at System.Xml.XmlTextReaderImpl.ParseEntityReference()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
   at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.Load(String filename)
   at Transformation.GetEcgTransformer(String filePath, String fileType, String Manufacture, String Producer) in D:'Transformation.cs:line 160

现在我需要用'and<'替换所有出现的&<,这样XML就可以成功处理而不会出现任何异常。

替换XML文件中的值

我就是这样做的,以便在Botz3000给出的答案的帮助下加载XML。

string oldText = File.ReadAllText(filePath);
string newText = oldText.Replace("&<", "and<");
File.WriteAllText(filePath, newText, Encoding.UTF8);
xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);

Xml文件无效,因为&需要转义为&amp;,所以您不能只是加载Xml而不得到错误。如果您以纯文本形式加载文件,则可以这样做:

string invalid = File.ReadAllText(filename);
string valid = invalid.Replace("&<", "and<");
File.WriteAllText(filename, valid);

如果您可以控制Xml文件的生成方式,那么您应该通过将&转义为&amp;或将其替换为"and"来解决该问题。