将XML文件内容保存到String或StringBuilder

Cha*_*nna 5 c#


我想将XML文件的全部内容保存到字符串或字符串构建器中.请让我知道我怎么能这样做?

我的函数需要将XML文件内容完全复制或保存到字符串或字符串构建器.
它是外部内容(XML文件).之后我需要更改xml文件的内容(onf字段)我可以通过C#实现它.请告诉我.

我有以下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>";
Run Code Online (Sandbox Code Playgroud)

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

此致,
Channaa

Guf*_*ffa 7

将XML文件读入字符串很简单:

string xml = File.ReadAllText(fileName);
Run Code Online (Sandbox Code Playgroud)

要访问内容,您可以将其读入XmlDocument:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
Run Code Online (Sandbox Code Playgroud)


Ang*_*wal 6

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();
Run Code Online (Sandbox Code Playgroud)

现在,使用xDocument,您可以操作XML并将其保存回来 -

           xDocument.Save(@"C:\MyFile.xml");
Run Code Online (Sandbox Code Playgroud)