Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert inner text into empty xml element?

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?

like image 579
user1750293 Avatar asked Oct 16 '12 14:10

user1750293


1 Answers

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");
like image 108
Anirudha Avatar answered Sep 20 '22 06:09

Anirudha