【问题标题】:How to write content in an existing .xml file which is totally empty?如何在完全空的现有 .xml 文件中写入内容?
【发布时间】:2014-10-13 15:47:55
【问题描述】:

如何在现有的完全为空的 .xml 文件中写入内容? 我正在创建一个名为 newXML.xml 的新文件并将其路径存储在字符串中,如下所示:

File.Create(Application.StartupPath + @"newXML.xml");   
string path=Application.StartupPath + @"newXML.xml";

现在我有一些带有 xml 标签的 xml 数据,我想将这些数据存储到一个字符串中,并将这些数据写入我创建的名为 newXML.xml 的新文件中。

我要存储在字符串中的数据如下...

<configuration>
<system.runtime.remoting>
<application name="Server">
     <client>
     </client>
</application>
</system.runtime.remoting>
</configuration>

我该怎么做?

【问题讨论】:

  • 这样做吗?为什么不填写XDocument,然后用xDocument.Save(Application.StartupPath + @"newXML.xml") 之类的东西保存呢? msdn.microsoft.com/library/bb345830.aspx
  • 我处于学习阶段,无法使用 xDocument 。无论如何我可以将所有信息存储在一个字符串中?
  • 您可以简单地将File.WriteAllText 与UTF8 编码一起使用。这是将字符串写入文件的(最简单的)方法之一。这对于学习来说是可以的,但是稍后,如果您使用“真实”的 XML 数据,您绝对应该使用 LINQ to XML 类。
  • 如果将 XML 数据放入字符串中,则需要对引号进行转义。比如string xmlData = "&lt;root&gt;&lt;element attribute=\"value\"&gt;&lt;/element&gt;&lt;/root&gt;";——看看字符串中的引号"是如何被转义的,现在是\"

标签: c# .net xml


【解决方案1】:

看看XDocument 类。

XDocument xml = new XDocument(
    new XElement("configuration",
        new XElement("system.runtime.remoting",
            new XElement("application",
                new XAttribute("name", "Server"),
                new XElement("client")))));
xml.Save(//Stream to save file);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2020-06-30
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多