2012-08-31 31 views
0

我想創建xmlfile來存儲信息我正在使用以下代碼,如何在此代碼中指定編碼,當我嘗試以另一種形式閱讀此文件時,日文中的字符是扭曲。如何在創建xml文件時包含編碼

XmlDocument writer = new XmlDocument(); 
      XmlElement root = writer.CreateElement("PatientFile"); 
      writer.AppendChild(root); 

      XmlElement ID = writer.CreateElement("ID"); 
      if (!string.IsNullOrEmpty(_a2Data.CurrentRecordId)) 
      { 
       ID.InnerText = _a2Data.CurrentRecordId; 
      } 
      root.AppendChild(ID); 

      XmlElement patientID = writer.CreateElement("PatientID"); 
      if (!string.IsNullOrEmpty(_a2Data.PatId)) 
      { 
       patientID.InnerText = _a2Data.PatId; 
      } 
      root.AppendChild(patientID); 

      XmlElement patientName = writer.CreateElement("PatientName"); 
      if (!string.IsNullOrEmpty(_a2Data.PatName)) 
      { 
       patientName.InnerText = _a2Data.PatName; 
      } 
      root.AppendChild(patientName); 

      XmlElement room = writer.CreateElement("Room"); 
      if (!string.IsNullOrEmpty(_a2Data.RoomName)) 
      { 
       room.InnerText = _a2Data.RoomName; 
      } 
      root.AppendChild(room); 
      string folderName = ConfigurationManager.AppSettings["PatientXMLFiles"]; 
      if (!Directory.Exists(folderName)) 
       Directory.CreateDirectory(folderName); 

      string fileName = ConfigurationManager.AppSettings["PatientXMLFiles"] + @"\" + _a2Data.CurrentRecordId + ".xml"; 
      writer.Save(fileName); 
+1

你能試試嗎? http://stackoverflow.com/questions/157646/best-way-to-encode-text-data-for-xml –

+0

請顯示您的XML閱讀代碼,因爲它是可以解決問題的地方。你所顯示的代碼沒有什麼特別的錯誤(你也可以安全地將所有的樣本切割成3-4行)。 –

回答

3

您正在使用Save方法,它採用一個文件名作爲參數的重載。此方法使用UTF-8編碼。創建一個XML聲明創建根前:

// ... 

XmlDeclaration documentType = writer.CreateXmlDeclaration("1.0", "utf-8", null); 
writer.AppendChild(documentType); 

XmlElement root = writer.CreateElement("PatientFile"); 
writer.AppendChild(root); 

// ... 

作爲一個側面說明,如果你想擁有過該文件有,你需要使用Save的其他重載之一,創建的編碼控制方法。

-1

我用這些行,現在可

  XmlDocument writer = new XmlDocument(); 
      XmlDeclaration xmldecl; 
      xmldecl = writer.CreateXmlDeclaration("1.0", null, null); 
      xmldecl.Encoding = "UTF-8"; 

      writer.AppendChild(xmldecl);