我试图读取与我的帖子ID字符串(不为null)属性匹配的XML数据,但是即使我尝试了几次,它也会返回null。
protected void Update_btn_click(object sender, EventArgs e)
{
String new_title = newtitle.Text.ToString();
String new_description = update_des.Value.ToString();
String postid = Request.QueryString["pid"];
System.Diagnostics.Debug.WriteLine(postid);
string filename = "C:\\Users\\user\\Source\\Repos\\FoodBlog\\FoodBlog\\Data\\blog_post.xml";
XmlDocument xml_doc = new XmlDocument();
xml_doc.Load(filename);
XmlTextReader xtr = new XmlTextReader(filename);
XmlNodeList elemList = xml_doc.GetElementsByTagName("post");
for (int i = 0; i < elemList.Count; i++)
{
string getValue = elemList[i].Attributes[postid].ChildNodes[1].InnerText;
System.Diagnostics.Debug.WriteLine(getValue);
}
}
XML数据:
<Posts>
<post pid="pid2623">
<title>Test</title>
<description>Test</description>
<subtitle>Test</subtitle>
<date>7/29/2018 12:00:00 AM</date>
<author>est</author>
</post>
</Posts>
错误:
答案 0 :(得分:0)
我认为您的代码有问题
您需要修改这些行,因为在for循环中,您正在查找包含名称为 pid2623 的属性的元素,但实际上您需要查找其 pid < / strong>属性包含值 pid2623
XmlNodeList elemList = xml_doc.GetElementsByTagName("post");
for (int i=0;i<elemList.Count; i ++)
{
string getValue = elemList[i].Attributes[postid].ChildNodes[1].InnerText;
System.Diagnostics.Debug.WriteLine(getValue);
}
到
XmlNode elemList = xml_doc.SelectSingleNode("/Posts/Post[@pid='"+ postid +"']");
答案 1 :(得分:0)
使用Linq To SQL IMHO更容易:
XDocument xml_doc = XDocument.Load(filename);
foreach (var p in xml_doc.Elements("Posts"))
{
System.Diagnostics.Debug
.WriteLine((string)p.Element("post").Attribute("pid"));
}
,您可以查询这样的特定帖子:
var post = from p in xml_doc.Elements("Posts")
where (string)p.Element("post").Attribute("pid") == postid
select p.Element("post");