如何在xml中逐行添加,编辑和删除

时间:2015-09-20 11:01:13

标签: c# xml

我有字符串XML。我加载到XmlDocument。如何通过最简单的方法逐行添加,编辑和删除,因为我只知道应该编辑的行。用XML作为XML更好的工作,或者更好地使用XmlDocuments?

    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 个答案:

答案 0 :(得分: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);