gpt4 book ai didi

c# - 如何从模板-c#创建xml

转载 作者:数据小太阳 更新时间:2023-10-29 02:51:52 26 4
gpt4 key购买 nike

我有一个这样的xml模板

<User>
<UserId></UserId>
<UserName></UserName>
<Roles>
<Role></Role>
<Roles></Role>
</Roles>
</User>

形成这个 xml 模板文件,我想动态地生成一个 xml。我该怎么做。

输出的 xml 应该是这样的

<User>
<UserId>user1</UserId>
<UserName>fr</UserName>
<Roles>
<Role>abc</Role>
<Role>def</Role>
</Roles>
</User>

我怎样才能做到这一点。我需要在模板文件中进行哪些更改。如何使用 C# 从这个 tempalte xml 文件读取和创建 xml。

最佳答案

您可以使用 XmlSerializer并根据模板创建一个具有属性的简单类:

public class User
{
public UserId{get;set;}

...
}

并将该类序列化为 XML 文件。

有一个很好的例子here .

选项#2:
如果出于某种原因您不想使用 XmlSerializer,请使用 XmlWriter - 为了防止忘记关闭元素,我建议您使用“AutoClose”XmlWriter - 我已经在博客中介绍过如何在我的博客上创建这个简单的类 - XmlWriter that automatically close elements using IDisposable

关于c# - 如何从模板-c#创建xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com