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?


使用LINQ2XML。它是对其他XML API的完全替代,比如肮脏的老白痴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");

Check if the address2 xml tag is empty. If yes , go to its parent and remove the tag then again add the same tag with value. If no , assign the inner text to address2.

let me know if you need the code.


Use the SetElementValue method in LINQ to XML:

XDocument doc = XDocument.Load(FilePath); //replace with xml file path
IEnumerable<XElement> buyersList = doc.Descendants("Table1"); //get the table node.
var ele = (from buyer in buyersList
           where buyer.Element("buyername").Value == "CompanyA"
           select buyer).SingleOrDefault(); 
ele.SetElementValue("address1", "SomeInfo");
ele.SetElementValue("address2", "SomeInfo");
doc.Save(FilePath);

DEMO : http://ideone.com/Cf7YI

链接地址: http://www.djcxy.com/p/11308.html

上一篇: ExpressionEngine:帮助订购反向相关条目

下一篇: 如何将内部文本插入空的xml元素?