I have an xmldocument that i'm loading xml in to.
The xml looks like this:
<Table1>
<buyer_id>0</buyer_id>
<buyername>CompanyA</buyername>
<address1>123 Simpsons Dr.</address1>
<address2/>
<city>Springfield</city>
<state>ST</state>
<postalcode>12345</postalcode>
<eaddress/>
<phone/>
<fax/>
</Table1>
I'm looping through looking at each CompanyA entry and setting innertext accordingly. I'm using the following code to insert inner text into elements that meet the criteria:
XmlDocument dom = new XmlDocument();
dom.LoadXml(xmlString);
XmlNodeList elemList = dom.GetElementByTagName("Table1");
for(int i = 0; i < elemList.Count; i++)
{
if(dom.GetElementsByTagName("buyername").Item(i).InnerText.Contains("CompanyA")
{
dom.GetElementsByTagName("address1").Item(i).InnerText = "SomeInfo";
}
}
Using the above code, the value of address1(123 Simpsons Dr.) would be replaced by "SomeInfo". I would like to instead insert "SomeInfo" into the address2 element but when I try using:
dom.GetElementsByTagName("address2").Item(i).InnerText = "SomeInfo";
I get an error. I'm able to insert innertext into any element that already has a value but I cannot when the element is empty (such as <address2/>
). Thoughts?
Use LINQ2XML.It's a complete replacement to other XML api's like the dirty old idiot XmlDocument
XElement doc=XElement.Load("yourXml.xml");
foreach(var elm in doc.Descendants("Table1"))
{
if(elm.Element("buyername").Value=="CompanyA")
elm.Element("address2").Value="SomeInfo";
}
doc.Save("yourXml.xml");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With