c# - 如何将字符串变量的值保存到 .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>
解决方案
先生,您来了。使用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>
推荐阅读
- c# - 在验证方法中检查属性时 C# 不可为空的编译器警告
- ios - 如何检测 URL 是否已粘贴/输入到 UITextView?斯威夫特 iOS
- flutter - Flutter:setState 不更新内部小部件
- java - 从网页运行java程序
- string - 使用 Grep 输出字符串
- java - 我可以根据属性对对象列表进行分组,并在流中一次将这些新列表传递给方法吗?
- database - Flutter:在真实设备iOS中手动下载/导出本地数据库
- c# - IDbCommandTreeInterceptor.TreeCreated:如何创建表达式等价集名称 = 名称 + '后缀'
- dart - Flutter:我是否需要取消 Strem 控制器?
- javascript - 如何在此应用程序中启动 mogodb?