-2

我想通过 QueryString 根据 id xmlelement 值过滤我的代码,但它似乎不起作用!!!

XmlDocument xdoc = new XmlDocument();
xdoc.Load(filepath);

XmlNode root = xdoc.DocumentElement;
XmlNode idNode = root.SelectSingleNode("/students/student/id");

           if (idNode.Value == null){create a new xml node}
else if (idNode.Value != null) {update the xml element with the value of id)

我试图解释它的问题,这是链接...

https://stackoverflow.com/questions/13607387/edit-xml-elements-of-a-specific-node-based-on-its-id-element-asp-net-page

4

1 回答 1

1

如果我理解正确,您想添加学生元素,如果没有指定 id 的学生(并且可能向学生节点添加一些数据)。这是 Linq to xml 解决方案:

int id = 2;
XDocument xdoc = XDocument.Load(filepath);
XElement student = xdoc.Descendants("student")
        .Where(s => (int)s.Element("id") == id)
        .SingleOrDefault();

if (student == null)
{
    student = new XElement("student",
                        new XElement("id", id),
                        new XElement("first_name"),
                        new XElement("last_name")); // add other elements here
    xdoc.Root.Add(student);
}

student.Element("first_name").Value = TextBox_firstname.Text;
student.Element("last_name").Value = TextBox_lastname.Text;
// set other values here          

xdoc.Save(filepath);
于 2012-11-29T06:50:52.570 回答