2012-06-22 70 views
4


保存XML文件內容爲String或StringBuilder的

我想保存XML文件的一個字符串或StringBuilder的全部內容。請讓我知道我如何達到?

我的功能需要完全複製或保存XML文件內容到字符串或StringBuilder的。
這是外部內容(XML文件)。之後我需要改變xml文件我可以achive它通過C#的內容(ONF場)。請告訴我。

我有以下XML格式的內容,我想放在一個字符串,並將其傳遞給另一個函數以才達到我的工作。


 <wsa:Address xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address> 
     <wsa:ReferenceParameters xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsman="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd"> 
     <wsman:ResourceURI>http://schema.unisys.com/wbem/wscim/1/cim-   </wsa:ReferenceParameters> 
     </p:Source> 
    </p:INPUT>"; 

---------------------------------------- ----------

問候,
Channaa

+2

你嘗試過什麼?打開文件並獲取所有內容是最基本的操作之一... – walther

+0

爲什麼您需要將整個XML文件存儲在字符串中? '問題就像 - 讀取XML文件,更改元素/屬性並將其保存?'。如果是,那麼有大量的樣本可用。只需搜索它。就像'XDocument.Load(@「C:\ MyFile.xml」);' –

回答

5
using System.Xml.Linq; 

// load the file 
      var xDocument = XDocument.Load(@"C:\MyFile.xml"); 
// convert the xml into string (did not get why do you want to do this) 
      string xml = xDocument.ToString(); 

現在,使用xDocument,你可以操縱XML &保存回 -

  xDocument.Save(@"C:\MyFile.xml"); 
7

將XML文件讀取到一個字符串很簡單:

string xml = File.ReadAllText(fileName); 

的訪問內容,你會閱讀到如下:

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(xml); 
0

你爲什麼不直接讀取XML來XmlDocument

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load(xmlFilePath); 

當你需要XML作爲字符串,然後使用XmlNode.OuterXml屬性。

相關問題