2013-03-01 83 views
1

我們的應用程序需要處理XML文件。有些時候,我們收到值個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 

現在我需要替換所有出現&<''和'<',這樣就可以在沒有任何異常情況下成功處理XML。

回答

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); 
2

Xml文件無效,因爲&需要轉義爲&amp;,所以你不能只加載xml而不會出現錯誤。

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

如果你有過怎樣的XML文件,雖然產生的控制,你應該要麼逃避&&amp;或替換它解決這個問題:如果你加載的文件爲純文本雖然你可以這樣做正如你所說的"and"