gpt4 book ai didi

c# - 基于 xmlElement 编辑 xml 节点

转载 作者:数据小太阳 更新时间:2023-10-29 01:59:04 26 4
gpt4 key购买 nike

我试过两种方法,但都没有用..第一种方式::

string filepath = Server.MapPath[this is not a link]("XMLFile2.xml");
XmlDocument xdoc = new XmlDocument();
xdoc.Load(filepath);

XmlNode root = xdoc.DocumentElement;
XmlNode idNode = root.SelectSingleNode("/students/student/id");
if (idNode.Value == 9.ToString())
{
var nodeOfStudent = xdoc.SelectNodes("/students/student[@id='9']");
nodeOfStudent[1].InnerXml = TextBox_firstname.Text;
nodeOfStudent[2].InnerXml = TextBox_lastname.Text;
nodeOfStudent[3].InnerXml = TextBox_dob.Text;
nodeOfStudent[4].InnerXml = TextBox_class.Text;
nodeOfStudent[5].InnerXml = TextBox_section.Text;
nodeOfStudent[6].InnerXml = TextBox_telephone.Text;

}

第二种方式::

string filepath = Server.MapPath("XMLFile2.xml");
XmlDocument xdoc = new XmlDocument();
xdoc.Load(filepath);

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

xdoc.SelectSingleNode("/students/student[@id='10']/firstname").InnerXml = TextBox_firstname.Text;
xdoc.DocumentElement.AppendChild(firstname);
xdoc.SelectSingleNode("/students/student[@id='10']/lastname").InnerXml = TextBox_firstname.Text;
xdoc.SelectSingleNode("/students/student[@id='10']/dob").InnerXml = TextBox_firstname.Text;
xdoc.SelectSingleNode("/students/student[@id='10']/class").InnerXml = TextBox_firstname.Text;
xdoc.SelectSingleNode("/students/student[@id='10']/section").InnerXml = TextBox_firstname.Text;
xdoc.SelectSingleNode("/students/student[@id='10']/telephone").InnerXml = TextBox_firstname.Text;

xdoc.Save(filepath);

有什么不对吗我没看到...我的 xml 文件看起来像这样::

<students>
<student>
<id>1</id>
<first_name>ahmad</first_name>
<last_name>hani</last_name>
<DOB>12/5/1998</DOB>
<class>sixth</class>
<section>A</section>
<telephone>06555632</telephone>
</student>
</students>

我使用查询字符串从位于另一个页面的 gridView 加载值,使用“QueryString”...

提前致谢。

最佳答案

您可以使用 Linq to xml 轻松地做到这一点:

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

if (student != null)
{
student.Element("first_name").Value = TextBox_firstname.Text;
student.Element("last_name").Value = TextBox_lastname.Text;
student.Element("DOB").Value = TextBox_dob.Text;
student.Element("class").Value = TextBox_class.Text;
// etc
}

xdoc.Save(filepath);

关于c# - 基于 xmlElement 编辑 xml 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13604998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com