2015-09-20 68 views
0

我有字符串XML。我加載到XmlDocument。如何通過最簡單的方法逐行添加,編輯和刪除,因爲我知道只有我應該編輯的行。用字符串來處理XML會更好,或者更好地處理XmlDocuments?如何在xml中逐行添加,編輯和刪除

using System; 
    using System.Xml; 

    namespace testXMl 
    { 
     class Program 
     { 
      static void Main(string[] args) 
      { 
       string xml="<?xml version=\"1.0\"?>\r\n<application>\r\n<features>\r\n<test key=\"some_key\">\r\n</features>\r\n</application>"; 
       XmlDocument xm = new XmlDocument(); 
       xm.LoadXml(xml); 
       //Edit third line 
       //xm[3].EditName(featuresNew); 
       //xml->"<?xml version=\"1.0\"?>\r\n<application>\r\n<featuresNew>\r\n<test key=\"some_key\">\r\n</featuresNew>\r\n</application>" 

       //Add fourth line the Node 
       //xm[4].AddNode("FeatureNext"); 
       //xml->"<?xml version=\"1.0\"?>\r\n<application>\r\n<FeatureNext>\r\n<FeatureNext>\r\n</features2>\r\n<test key=\"some_key\">\r\n</features>\r\n</application>" 

       //Delete sixth line 
       //xm[6].DeleteNode; 
       //xml->"<?xml version=\"1.0\"?>\r\n<application>\r\n<FeatureNext>\r\n<FeatureNext>\r\n</features2>\r\n</features>\r\n</application>" 
      } 
     } 
    } 

謝謝,提前。

回答

1

您應該總是XDocument/XmlDocument一起使用的對象。關鍵知識是XPath查詢語言。

這是一個快速的XML速成教程。在調試器中運行,並在繼續操作時檢查XML變量。

var xml = new XmlDocument(); 
    xml.LoadXml(@"<?xml version='1.0'?> 
    <application> 
     <features> 
      <test key='some_key' /> 
     </features> 
    </application>"); 

// Select an element to work with; I prefer to work with XmlElement instead of XmlNode 
var test = (XmlElement) xml.SelectSingleNode("//test"); 
    test.InnerText = "another"; 
    test.SetAttribute("sample", "value"); 
var attr = test.GetAttribute("xyz"); // Works, even if that attribute doesn't exists 

// Create a new element: you'll need to point where you should add a child element 
var newElement = xml.CreateElement("newElement"); 
    xml.SelectSingleNode("/application/features").AppendChild(newElement); 

// You can also select elements by its position; 
// in this example, take the second element inside "features" regardless its name 
var delete = xml.SelectSingleNode("/application/features/*[2]"); 

// Trick part: if you found the element, navigate to its parent and remove the child 
if (delete != null) 
    delete.ParentNode.RemoveChild(delete); 
相關問題