2014-11-03 87 views
0

我有我試圖修改XML文檔...用C#的XML節點添加到一個現有的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); 
    } 
} 

任何指導將不勝感激。

+1

如果您要對XML進行大量修改,則應考慮使用XSLT。 XSLT將XML作爲輸入,並輸出該XML的「已轉換」版本。 – Andersnk 2014-11-03 21:10:16

回答

1

嘗試使用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>); 

讓我知道,如果你需要它的另一部分更多的幫助,我會很樂意幫助!

+0

最好的方法是解析包含該數據的文本文件,並使用該值插入它,每個值迭代地填充新的XElement對象。 – 2014-11-03 22:21:35

+0

往往不是這個問題,哈哈。當我遇到這些問題時,我有我的天才夥伴去。 – 2014-11-04 02:30:49

+0

任何*** Fluent *** for'Fetch XML'? _XML構造是一種痛苦_ https://github.com/tofi9/MSCRM-FetchXml/blob/master/Tofi9.FetchXml.Tests/DemoQueries.cs#L42 – Kiquenet 2016-10-19 09:37:15

相關問題