簡體   English   中英

使用C#將XML節點添加到現有XML文件

[英]Using C# to add an XML node to an exiting XML file

我有一個要修改的XML文檔...

 <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="contact">
    <attribute name="fullname" />
    <attribute name="telephone1" />
    <attribute name="contactid" />
    <order attribute="fullname" descending="false" />
    <filter type = "and">
      <condition attribute="parentcustomerid" operator="eq" uiname="Tardis Communications" uitype="account" value="{BB0D0E64-C85E-E411-9405-00155D1DEA05}" />
    </filter>
  </entity>
</fetch>

我想做的是插入此...

<filter type = "and">
<condition attribute="ownerid" operator= "eq-userid"/>
</filter>

在已經存在的“過濾器”標簽之間。 新的過濾器代碼來自另一個文件(.txt)。

我意識到這可能沒有道理,但是,我只想看看是否有可能。 如果是這樣,我以后可以四處走動。

這是我嘗試過的。

private void button1_Click(object sender, EventArgs e)
{
    XmlDataDocument doc = new XmlDataDocument();
    doc.Load(@"C:\Users\jellsworth\Downloads\mySampleXML.xml");
    //XmlNode node = null;
    foreach (XmlNode node in doc.SelectNodes("//filter/condition")) 
    {
        XmlElement mapNode = doc.CreateElement("filter");
        XmlAttribute newFilter = doc.CreateAttribute("lattitude");
        newFilter.Value = @"C:\Users\jellsworth\Downloads\playFilter.txt";
        mapNode.SetAttributeNode(newFilter);

        node.InsertBefore(mapNode, node.FirstChild);
    }
}

任何指導將不勝感激。

嘗試使用XDocument。

        // Load document
        XDocument myDoc = XDocument.Load(".\\Main.xml");

        // Select child element "entity" then select the child element of it you want which is "filter"
        XElement filterNode = myDoc.Root.Element("entity").Element("filter");

        //Example to iterate through all of the child nodes with the name condition
        foreach (var childNode in filterNode.Descendants("condition")) {
            // you could add another attribute to each of them
            childNode.SetAttributeValue("", "");
        }

        // Example element to add
        XElement newCondition = new XElement("condition");
        newCondition.SetAttributeValue("attribute", "parentcustomerid");
        newCondition.SetAttributeValue("operator", "eq");

        filterNode.Add(newCondition);
        myDoc.Save(".\\newFile.xml");

基本上,使用文件路徑作為字符串加載文檔

XDocument.Load("<pathToFile>");

選擇元素並向下鑽取就像設置一個新的XElement一樣簡單myElement = myDoc.root.Element("<Child element name>");

現在, myElement將始終代表該節點,並且也可以對其進行迭代。 要添加節點,只需調用諸如

myElement.Add(<new XElement with attributes set>);

如果您需要其他方面的幫助,請告訴我,我們很樂意為您提供幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM