将元素节点添加到xml文件c#

时间:2014-05-06 13:45:42

标签: c# xml

我正在尝试向节点添加一个新元素,该节点具有与输入相同的属性。我试过,但我开始用xml。我该怎么办?

旧的xml文件:

<Root>
 <Chatter Name="Dat" ID="1">
   <Content  Time="06/05/2014 2:00:08 PM">Send Content</Content>
   <Content  Time="06/05/2014 2:00:50 PM">Recieve Content</Content>
 </Chatter>
 <Chatter Name="Khang" ID="2">
    <Content  Time="06/05/2014 2:01:40 PM">Send Content</Content>
    <Content  Time="06/05/2014 2:02:00 PM">Recieve Content</Content>
 </Chatter>
 <Chatter Name="Khanh" ID="12">
    <Content Time="06/05/2014 2:03:10 PM">them moi</Content>
 </Chatter>
</Root>

我想向节点添加一个新元素,如果存在属性Name =“Khang”,那么这里是新的xml文件

<Root>
 <Chatter Name="Dat" ID="1">
   <Content  Time="06/05/2014 2:00:08 PM">Send Content</Content>
   <Content  Time="06/05/2014 2:00:50 PM">Recieve Content</Content>
 </Chatter>
 <Chatter Name="Khang" ID="2">
    <Content  Time="06/05/2014 2:01:40 PM">Send Content</Content>
    <Content  Time="06/05/2014 2:02:00 PM">Recieve Content</Content>
    <Content  Time="06/05/2014 2:20:40 PM">Send Content</Content>
 </Chatter>
 <Chatter Name="Khanh" ID="12">
    <Content Time="06/05/2014 2:03:10 PM">them moi</Content>
 </Chatter>
</Root>

非常感谢! 和我的代码

public static bool SaveMessage(string name, string content)
    {
        XmlDocument xmldoc = new XmlDocument();
        XmlNodeList xmlnode,xmlOldNode;
        xmldoc.Load(_fileXmlPath);
        xmlnode =xmlOldNode= xmldoc.GetElementsByTagName("Chatter");
        for (int i = 0; i < xmlnode.Count;i++ )
        {
            if (xmlnode[i].Attributes["Name"].Value == name)
            {      
                XmlElement elem = xmldoc.CreateElement("Name", "Content", name);                 
                elem.SetAttribute("Time", DateTime.Now.ToString());
                elem.InnerText = content;
                xmldoc.DocumentElement.AppendChild(elem);
                return true;
            }
        } 
        return false;        
  }

但它没有添加到xml文件

1 个答案:

答案 0 :(得分:0)

作为一个粗略的例子,以下内容适合您;

//First load the xml into a XDocument (can be a string or file for example)
var doc = XDocument.Load(xml);

//Then try and retrieve the Khang node
XElement khang = (from xml2 in doc.Descendants("Chatter")
                    where xml2.Attribute("Name").Value == "Khang"
                    select xml2).FirstOrDefault();

//If the Khang node exists, create a new Element and add it to the Khang node         
if(khang != null)
{
    XElement newNode = new XElement("Node");
    khang.Add(newNode);
}

详细说明:

  1. 首先将load xml放入XDocument

    var doc = XDocument.Load(xml);

  2. 然后尝试使用Linq To Xml检索Khang节点以选择Khang节点

    XElement khang = (from xml2 in doc.Descendants("Chatter") where xml2.Attribute("Name").Value == "Khang" select xml2).FirstOrDefault();

  3. 为Khang节点创建一个新的XElementAdd(如果存在)

    if(khang != null) { XElement newNode = new XElement("Node"); khang.Add(newNode); }