[英]Parse and Generate xml from template file (C#)
I have a template XML that looks something similar to this 我有一个看起来与此相似的模板XML
<a:Demographics>
<b:Id>
<c:IdValue></c:IdValue>
<c:IdScheme></c:IdScheme>
<c:IdType></c:IdType>
</b:Id>
</a:Demographics>
Using Visual Studio and c#, How can I parse the xml, then based on my current record, add my own data into c:IdValue
, c:IdScheme
and c:IdType
as these are required xml fields. 使用Visual Studio和c#,如何解析xml,然后根据当前记录将我自己的数据添加到
c:IdValue
, c:IdScheme
和c:IdType
因为这些是必填的xml字段。 They have been left blank in the template so that my the program will fill them I then need to save that as a new xml file but that should be straightforward once the values have been added. 它们在模板中留为空白,以便我的程序填充它们,然后我需要将其另存为新的xml文件,但是一旦添加了值就应该很简单。
I am open to using any library that can get the job done! 我愿意使用任何可以完成工作的库!
you can use System.Xml.Linq 您可以使用System.Xml.Linq
Load the Template 加载模板
XDocument Template = XDocument.Load("Template.xml");
Modify it 修改它
void AddData(string elemName, string value)
{
XElement element = Template.Root.Descendants("elemName").First();
element.Value = value;
}
and Save it 并保存
Template.Save("newXml.xml");
A valid XML must have namespace prefix declaration somewhere, I assume your XML has it. 有效的XML必须在某处具有名称空间前缀声明,我假设您的XML已有声明。 Then you can do something like this using
XDocument
: 然后,您可以使用
XDocument
:
XDocument doc = XDocument.Load("path_to_xml_file.xml");
XNamespace a = "http://uri.for.a.prefix.com";
XNamespace b = "http://uri.for.b.prefix.com";
XNamespace c = "http://uri.for.c.prefix.com";
XElement id = doc.Descendants(a+"Demographics")
.First()
.Element(b+"Id");
id.Element(c+"IdValue").Value = "new value here";
id.Element(c+"IdScheme").Value = "new scheme here";
id.Element(c+"IdType").Value = "new type here";
doc.Save("path_to_new_xml_file.xml");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.