如何在xml中逐行添加、编辑和删除节点

本文关键字:编辑 删除 节点 添加 逐行 xml | 更新日期: 2023-09-27 18:13:40

我有字符串XML。我加载到XmlDocument。我如何用最简单的方法逐行添加,编辑和删除,因为我只知道我应该编辑的行。它是更好的工作与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>"
            }
        }
    }

如何在xml中逐行添加、编辑和删除节点

您应该始终使用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);