Reputation: 293
I need to append a xml data to an xmldocument object. My code is like this
public xmlDocument Getdate(string s)
{ ...
return _prod
}
_prod = new XmlDocument();
string[] sn = {"first", "second"}
foreach(string s in sn)
{
_prod = Getdata(s);
// need the code to add the second loop to the xmldocument object "_prod"
}
first xml data would be:
<products>
<product>
<id>1</id>
<price>15</price>
</product>
</products>
second xml data would be:
<products>
<product>
<id>2</id>
<price>30</price>
</product>
</products>
i want the final xml object _prod(inside for-each) to be like this
<products>
<product>
<id>1</id>
<price>15</price>
</product>
<product>
<id>2</id>
<price>30</price>
</product>
</products>
Please suggest
Upvotes: 0
Views: 61
Reputation: 89305
One possible way, assuming you can have more than 2 XML documents to be merged :
_prod = new XmlDocument();
string[] sn = {"first", "second", "third"}
foreach(int i=0; i<sn.Length; i++)
{
//build _prod based on the first XML
if(i==0) _prod = Getdata(sn[i]);
//then from next XMLs, add <product> nodes as child of _prod's <products>
else
{
var _temp = Getdata(sn[i]);
//select <products> node from _prod
var product = _prod.SelectSingleNode("//products");
//select <product> nodes to be appended to _prod
var products = _temp.SelectNodes("//products/product");
foreach(XmlNode p in products)
{
product.AppendChild(p);
}
}
}
Upvotes: 1
Reputation: 121
Could you use Linq to XML instead and construct the whole XML in one go? Something like this:
var products = new XElement(
"products",
new string[] {"first", "second"}
.Select(s =>
{
var data = GetData(s);
return new XElement(
"product",
new XElement("id", data.Id),
new XElement("price", data.Price));
}));
var xmlString = products.ToString();
Upvotes: 0