在特定节点下添加XMLNode
本文关键字:添加 XMLNode 节点 | 更新日期: 2023-09-27 18:09:27
这是我的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>
- 我希望能够通过我的代码添加一个新的项目节点
- 我希望能够在给定项目名称的情况下创建一个新的图像节点
到目前为止,我的第一项任务是:
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);
}
任何帮助都将不胜感激。感谢
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")));