[英]Replacing values in XML file
Our application needs to process XML files. 我们的应用程序需要处理XML文件。 Some times we receive XMLs with values as follows:
有时我们会收到具有以下值的XML:
<DiagnosisStatement>
<StmtText>ST &</StmtText>
</DiagnosisStatement>
Because of &<
my application is not able to load XML correctly and throwing exception as follows: 由于
&<
我的应用程序无法正确加载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
Now I need to replace all occurrences of &<
with 'and<' so that XML can get processed successfully without any exceptions. 现在,我需要将所有出现的
&<
替换为'and <',以便XML可以成功处理而没有任何异常。
This is what I did in order to load XML with the help of answer given by Botz3000. 这是我在Botz3000给出的答案的帮助下加载XML的方法。
string oldText = File.ReadAllText(filePath);
string newText = oldText.Replace("&<", "and<");
File.WriteAllText(filePath, newText, Encoding.UTF8);
xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
The Xml file is invalid, because &
needs to be escaped as &
Xml文件无效,因为
&
需要以&
转义&
, so you cannot just load the xml without getting an error. ,因此您不能只加载xml而不会出现错误。 You can do it if you load the file as plain text though:
如果您将文件加载为纯文本格式,则可以执行以下操作:
string invalid = File.ReadAllText(filename);
string valid = invalid.Replace("&<", "and<");
File.WriteAllText(filename, valid);
If you have control over how the Xml file is generated though, you should fix that issue by either escaping the &
as &
如果您可以控制Xml文件的生成方式,则应通过将
&
转义为&
来解决该问题&
or by replacing it with "and"
as you said. 或如您所说,将其替换为
"and"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.