添加多个XmlElement.LastChild.InnerText

时间:2012-10-02 14:26:22

标签: c# xml c#-4.0

我有一个功能,我想在节点中添加多个'值'。这是功能:

 private void GetCategory(DataRow reader, XmlElement myNode)
    {
        foreach (DataRow categoryRow in reader.GetChildRows("Article_Category"))
        {
            myNode.LastChild.InnerText = categoryRow["CATEGORY_NAME"].ToString();
        }
    }

myNode.OuterXml如下所示:

<field itemid="{2C16342E-7662-432B-9895-5EDB15914D7F}" language="en" version="1" 
fieldid="{1F5956D6-EABE-4F74-A248-B25B7EE90350}" name="Categories" title=""
type="Multilist" source="/sitecore/content/data/Categories" section="Content" 
tooltip=""><value>US</value></field>

我想看起来像这样:

<field itemid="{2C16342E-7662-432B-9895-5EDB15914D7F}" language="en" version="1" 
fieldid="{1F5956D6-EABE-4F74-A248-B25B7EE90350}" name="Categories" title=""
type="Multilist" source="/sitecore/content/data/Categories" section="Content" 
tooltip=""><value>US</value><value>China</value><value>India</value></field>

我添加了这个功能:

 foreach (DataRow categoryRow in reader.GetChildRows("Article_Category"))
        {
            var newNode = myNode.OwnerDocument.CreateElement("Value");
            newNode.InnerText = categoryRow["CATEGORY_NAME"].ToString();
            myNode.AppendChild(newNode);

        }

它不起作用becoz这就是我的XML的样子:

 <field itemid="{9259D344-3500-4887-9CDF-F00876F20F2B}" language="en" version="1"
 fieldid="{1F5956D6-EABE-4F74-A248-B25B7EE90350}" name="Country" title="" 
 type="Multilist" source="/sitecore/content/data/Countries" section="Content"
 tooltip=""><value /><Value>Currency Markets</Value></field>

这是一个'value'标记,不允许加起来。

1 个答案:

答案 0 :(得分:1)

您当前的代码会覆盖LastChild的文本。您需要添加节点,

    //untested
    foreach (DataRow categoryRow in reader.GetChildRows("Category"))
    {
      //myNode.LastChild.InnerText = categoryRow["CATEGORY_NAME"].ToString();

        var newNode = myNode.OwnerDocument.CreateElement("value");
        newNode.InnerText = categoryRow["CATEGORY_NAME"].ToString();
        myNode.AppendChild(newNode);
    }