首页 > 解决方案 > 如何将字符串变量的值保存到 .xml 文件中?

问题描述

我无法将字符串变量的值写入XElement.xml 文件。

我试过使用System.IO: XDocument,XElement

代码.cs:

string variable ="sth";
XDocument xml_cip_c1 = new XDocument(
    new XComment("document"),
    new XElement("new root"),
    new XElement("name", variable)
);

结果.xml:

<!--document-->
<new root>
    <name />
</new root>

标签: c#xmlwpfxaml

解决方案


先生,您来了。使用Value属性:

var yourVariable = "ABC";
XDocument xml_cip_c1 = new XDocument(
    new XComment("document"),
    new XElement("new_root",
    new XElement("name") { Value = yourVariable}));

这将产生以下输出:

<?xml version="1.0" encoding="utf-8"?>
<!--document-->
<new_root>
  <name>ABC</name>
</new_root>

但是,如果您想将 Attribute 添加到您的 xml 元素,请使用以下代码XAttribute

XDocument xml_cip_c1 = new XDocument(
    new XComment("document"),
    new XElement("new_root",
    new XElement("name", new XAttribute("name", yourVariable))));

然后你会得到下面的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<!--document-->
<new_root>
  <name name="ASD" />
</new_root>

推荐阅读