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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11155512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:46:08  来源:igfitidea点击:

Saving XML file content to String or StringBuilder

c#

提问by Channa



I want to save The whole content of XML file to a string or stringbuilder. Please let me know how can i achive that??

我想将 XML 文件的全部内容保存到字符串或字符串生成器中。请让我知道我怎样才能做到这一点??

My Function needs to copy or Save a XML file content Completely to string or stringbuilder.
It is External Content(XML File).After that I need to change the Content(onf field ) of the xml file Can i achive it through C#. please let me know.

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

I Have following content in XML format , i want to put into one string and pass that to another Function in order to achive my Work.

我有以下 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>";

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

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

Regards,
Channaa

问候,
查娜

采纳答案by Angshuman Agarwal

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

Now, using xDocument, you can manipulate the XML & save it back -

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

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

回答by Guffa

Reading an XML file into a string is simple:

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

string xml = File.ReadAllText(fileName);

The to access the content, you would read it into an XmlDocument:

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

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

回答by ABH

Why don't you directly read XML to XmlDocument

为什么不直接读取XML到XmlDocument

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

When you need XML as string then use XmlNode.OuterXmlproperty.

当您需要 XML 作为字符串时,请使用XmlNode.OuterXml属性。