Reputation: 1491
I have a template XML that looks something similar to this
<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. 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.
I am open to using any library that can get the job done!
Upvotes: 0
Views: 2788
Reputation: 89285
A valid XML must have namespace prefix declaration somewhere, I assume your XML has it. Then you can do something like this using 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");
Upvotes: 1
Reputation: 2430
you can use 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");
Upvotes: 1