在特定节点下添加XMLNode

时间:2014-06-19 13:41:53

标签: c# xml linq-to-xml

这是我的XML结构

<?xml version="1.0" encoding="utf-8"?>
<Projects xmlns="urn:projects-schema">
    <Project>
        <Name>Project1</Name>
        <Images>
            <Image Path="D:/abc.jpg"></Image>
        </Images>
    </Project>       
</Projects>
  1. 我希望能够通过我的代码添加新的项目节点
  2. 我希望能够在给定项目名称
  3. 的情况下创建新的图像节点

    到目前为止我的第一项任务是:

    try
    {
        var filename = Server.MapPath("~/App_Data/Projects.xml");
        var doc = new XmlDocument();
    
        if (System.IO.File.Exists(filename))
        {
            if (!ProjectExists(projectName))
            {
                doc.Load(filename);
                var root = doc.DocumentElement;
                var newElement = doc.CreateElement("Project");
                root.AppendChild(newElement);
    
                root = doc.DocumentElement;
                newElement = doc.CreateElement("Name");
                var textNode = doc.CreateTextNode(projectName);
    
                root.LastChild.AppendChild(newElement);
                root.LastChild.LastChild.AppendChild(textNode);
    
                doc.Save(filename);
            }
            else
                throw new ApplicationException("Project already exists");
            doc = null;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    

    但我正在努力争取第二部分。这就是我到目前为止所做的:

    if (System.IO.File.Exists(projectFilename))
    {
        doc.Load(projectFilename);
        XmlNode root = doc.DocumentElement;
    
        XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
        nsManager.AddNamespace("prj", "urn:projects-schema");
    
        root = root.SelectSingleNode("descendant::prj:Project[prj:Name='" + projectName + "']", nsManager);
    }
    

    任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

XElement projects = XElement.Parse (
@"<Projects xmlns='urn:projects-schema'>
    <Project>
        <Name>Project1</Name>
        <Images>
            <Image Path='D:/abc.jpg'></Image>
        </Images>
    </Project>       
</Projects>");

对于任务1,可以按如下方式完成:

projects.LastNode.AddAfterSelf(new XElement("Project", 
                                 new XElement("Name", "Project2"),
                                 new XElement("Images",
                                    new XElement("Image", "", new XAttribute("Path", "C:/abc.jpg"))
                                 )));

任务2:

projects.Descendants("Name")
    .Where(x => x.Value == projectName).FirstOrDefault()
    .AddAfterSelf(new XElement("Images",
                       new XElement("Image", "", new XAttribute("Path", "C:/def.jpg"))
                    )
                );

编辑:检查是否存在Images元素并添加带有属性的子Image元素

projects.Descendants("Project")
    .Where(x => x.Elements("Images").Any())
    .Descendants("Images").FirstOrDefault()
    .Add(new XElement("Image", "", new XAttribute("Path", "D:/xyz.jpg")));