4

I have a xml template like this

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

Form this xml template file,dynamicaly i want to generate an xml.How can i do this.

Output xml should look like this

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

How can i achieve this.What all changes i need to make in template file.How to read and create xml from this tempalte xml file using c#.

4

4 回答 4

6

序列化是一种选择,但如果你真的需要一个模板,你可以使用这个https://github.com/beto-rodriguez/Templator

这是一个例子

C#

UserClass user = new UserClass();
user.UserId = 1;
user.UserName = "my name";
User.Roles = new List<string>(){"admin", "sales"};
//some other properties...    

var compiler = new Compiler()
            .AddElementToScope("user", user);

var compiled = compiler.CompileXml(@"C:\...\myXml.xml")

XLM 源

<User>
  <UserId>{{user.UserId}}</UserId>
  <UserName>{{user.UserName}}</UserName>
  <Roles Tor.Repeat="role in user.Roles">
    <Role>{{role}}</Role>
  <Roles></Role>
  </Roles>
</User>

编译

<User>
  <UserId>1</UserId>
  <UserName>my name</UserName>
  <Roles>
    <Role>admin</Role>
    <Role>sales</Role>
  <Roles></Role>
  </Roles>
</User>

你也可以从 Nuget 安装它:

Install-Package SuperXML
于 2015-08-07T06:01:25.797 回答
5

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

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

   ...
}

并将类序列化为 XML 文件。

这里有一个很好的例子。

选项 #2
如果由于某种原因您不想使用XmlSerializeruse XmlWriter- 为了防止忘记关闭元素,我建议您使用“AutoClose”XmlWriter - 我在我的博客上写过关于如何创建这个简单类的博客 - XmlWriter使用 IDisposable 自动关闭元素

于 2012-04-04T07:18:04.687 回答
0

var templateXML = "C://template.xml"//full path for the template xml XmlDocument doc = new XmlDocument(); FileStream fs = new FileStream(templateXML, FileMode.Open, FileAccess.Read); doc.Load(fs); XmlNode node = doc.DocumentElement; XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("pf", "http://www.example.com/abc"); node = doc.DocumentElement; nodeName = "/pf:Message/pf:User/pf:UserID"; node.SelectSingleNode(nodeName, nsmgr).InnerXml = "user1";put you custom value nodeName = "/pf:Message/pf:User/pf:UserName";
node.SelectSingleNode(nodeName, nsmgr).InnerXml = "fr";put you custom value .... ..... ....... var postData = node.ParentNode.InnerXml; postData = node.OuterXml;

于 2016-09-29T11:19:22.767 回答