【发布时间】:2015-01-19 11:29:17
【问题描述】:
我需要创建几个具有相同子节点的 xml 节点,但每个节点的名称应该不同,即
<Rootnode>
<somename1>
<testFilename><![CDATA[some-name]]></testFilename>
<parentDirectory><![CDATA[some-path]]></parentDirectory>
</somename1>
<somename2>
<testFilename><![CDATA[some-diff-name]]></testFilename>
<parentDirectory><![CDATA[some-diff-path]]></parentDirectory>
</somename2>
<somename3>
<testFilename><![CDATA[some-diff-name]]></testFilename>
<parentDirectory><![CDATA[some-diff-path]]></parentDirectory>
</somename3>
</Rootnode>
“somename”将作为字符串从另一个函数中获取
需要创建此节点的模板,因为节点数将是 100 通过使用序列化,我正在这样做
public class template1
{
public template1()
{
}
private String Filename;
private String Parentpath;
public System.Xml.XmlCDataSection testFilename
{
get
{
return new System.Xml.XmlDocument().CreateCDataSection(Filename);
}
set
{
this.Filename = value.Value;
}
}
public System.Xml.XmlCDataSection parentDirectory
{
get
{
return new System.Xml.XmlDocument().CreateCDataSection(Parentpath);
}
set
{
this.Parentpath = value.Value;
}
}
}
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)//will vary as per the no. of nodes to be generated
{
XmlDocument xdoc = new XmlDocument();
XmlCDataSection FCData, PCData;
String fname, pname;
fname = "some file name";
FCData = xdoc.CreateCDataSection(fname);
template1 a = new template1();
a.testFilename = FCData;
pname = "some path";
PCData = xdoc.CreateCDataSection(fname);
a.parentDirectory = PCData;
Serialize(a);
}
}
static public void Serialize(template1 t)
{
XmlSerializer serializer = new XmlSerializer(typeof(template1));
using (TextWriter writer = new StreamWriter(@"C:\\abc\\xelname.xml",true))
{
serializer.Serialize(writer, t);
}
}
}
这个生成的输出文件需要不同的名字而不是那个模板1
<?xml version="1.0" encoding="utf-8"?>
<template1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<testFilename><![CDATA[some file name0]]></testFilename>
<parentDirectory><![CDATA[some file name0]]></parentDirectory>
</template1>
<?xml version="1.0" encoding="utf-8"?>
<template1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<testFilename><![CDATA[some file name1]]></testFilename>
<parentDirectory><![CDATA[some file name1]]></parentDirectory>
</template1>
<?xml version="1.0" encoding="utf-8"?>
<template1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<testFilename><![CDATA[some file name2]]></testFilename>
<parentDirectory><![CDATA[some file name2]]></parentDirectory>
</template1>
以及如何忽略 template1 节点的属性
【问题讨论】:
-
作为一个非常基本的起点,请考虑一种方法,该方法接受您所需的节点名称,并返回一个带有属性集和附加子节点的节点。
-
需要创建模板,这样我就可以将值动态填充到节点中。节点的格式不会改变,只是值会不同。
-
我最初可能误解了您的要求 - 您是在问如何创建一个与您的数据“邮件合并”然后附加到另一个 xml 文档中的现有节点的 xml 模板?
-
是的..就像只是节点的名称会不同..