Setting XML nested nodes from C# with XElement
I'm modifying some legacy code and need to parse/write to XML with C#. I'm trying to set the value of a nested element but am not getting any joy. It should be very simple but I'm not sure what I'm doing wrong.
Here is the XML template:
<my:productReport>
<my:productId>1</my:productId>
<my:company>MyCompany</my:company>
<my:productPerson>
<my:productPersonId xsi:nil="true"></my:productPersonId>
<my:productPersonName></my:productPersonName>
</my:produc开发者_高级运维tedBy>
</my:productReport>
I can set the company no problem with:
XElement companyEle = doc.Root.Element(myNameSpace + "company");
companyEle.Value = value;
But how can I add a product person ID and Name? There may be more than one personID/personName elements to be added.
Are you looking for something like this? You mentioned needing to set and add, sorry if I misunderstood. Also, if you didn't notice, the template you gave has the wrong closing tag for productPerson.
//Get collection of productPerson elements
IEnumerable<XElement> prodPersons = productReport.Elements("productPerson");
foreach(XElement pp in prodPersons)
{
//Set values
pp.Element("productPersonId").Value = "1";
pp.Element("productPersonName").Value = "xxx";
}
//Add a productPerson element
XElement prodPersonEle =
new XElement("productPerson",
new XElement("productPersonId","3"),
new XElement("productPersonName", "Somename")
);
//Add prodPersonEle to whatever parent it belongs.
精彩评论