[英]Deleting Root Element and its children based off attribute value XML
我试图在选择被删除时从文件中删除学生元素。 问题是,它只删除孩子而不是父母。
XML 文件:
<StudentRecord>
<Student StudentNum="S0001">
<Name>John Smith</Name>
<Status>Active</Status>
<Courses>
<Course Code="TSS8257">
<Title>Design</Title>
<Grade>79.00</Grade>
</Course>
<Course Code="ART8253">
<Title>Art</Title>
<Grade>90.00</Grade>
</Course>
<Course Code="CSF8251">
<Title>Animations</Title>
<Grade>89.00</Grade>
</Course>
</Courses>
</Student>
<StudentRecord>
CS代码:
string xmlFilePath = Path.GetFullPath("Data/StudentRecord.xml");
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
XmlNodeList nodes = doc.GetElementsByTagName("Student");
XElement root = XElement.Load(xmlFilePath);
foreach (XmlNode node in nodes)
{
foreach (XmlAttribute attribute in node.Attributes)
{
if ((attribute.Name == "StudentNum") && (attribute.Value == id))
{
node.RemoveAll();
break;
}
}
}
//save xml file.
doc.Save(xmlFilePath);
我在 XML 文件中收到的 output:
<Student></Student>
我想要的 output 适用于所有内容,包括要删除的<Student></Student>
。
我过去的尝试是使用 linQ,它没有做任何事情:
var Student = xdoc.Elements()
.Descendants("Student")
.Where(e => (string)e.Attribute("StudentNum") == id);
foreach (var elem in Student)
{
elem.Remove();
}
您对node.RemoveAll();
的调用正在做它应该做的事情,即删除节点的所有子节点及其所有属性。 它不会删除节点。 您必须从父节点执行此操作。 像这样的东西。
node.ParentNode.RemoveChild(node);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.