我们的应用程序需要处理XML文件.有时我们会收到值如下的XML:
<DiagnosisStatement>
<StmtText>ST &</StmtText>
</DiagnosisStatement>
Run Code Online (Sandbox Code Playgroud)
由于&<我的应用程序无法正确加载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
Run Code Online (Sandbox Code Playgroud)
现在我需要&<用'和< 替换所有出现的内容,以便成功处理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);
Run Code Online (Sandbox Code Playgroud)