1

我们的应用程序需要处理 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 可以成功处理而没有任何异常。

4

2 回答 2

5

这就是我在 Botz3000 给出的答案的帮助下加载 XML 所做的。

string oldText = File.ReadAllText(filePath);
string newText = oldText.Replace("&<", "and<");
File.WriteAllText(filePath, newText, Encoding.UTF8);
xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
于 2013-03-20T12:21:39.607 回答
2

Xml 文件无效,因为&需要转义为&amp;,所以你不能只加载 xml 而不会出错。如果您将文件加载为纯文本,则可以这样做:

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

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

于 2013-03-01T08:18:40.457 回答