我正在使用LINQ编写和读取XML数据。读取部分可以,但无法正常工作。
我的xml中的发布数据正在正确加载,但是一旦用户尝试保存新更改,数据仍保持不变。请问为什么?
读取帖子数据:
public partial class EditPost : System.Web.UI.Page
{
private void Page_Load(object sender, EventArgs e)
{
string new_title = newtitle.Text.ToString();
string new_description = update_des.Value.ToString();
string path = "C:\\Users\\user\\Source\\Repos\\FoodBlog\\FoodBlog\\Data\\blog_post.xml";
string postid = Request.QueryString["pid"];
if (postid != null)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
XDocument xdoc = XDocument.Load(fs);
var post = from p in xdoc.Descendants("post")
select new {
Title = p.Element("title"),
Subtitle = p.Element("subtitle"),
Desc = p.Element("description"),
PID = p.Element("pid")
};
foreach (var ePosts in post) {
if (ePosts.PID.Value == postid) {
newtitle.Text = ePosts.Title.Value;
Subtitle.Value = ePosts.Subtitle.Value;
update_des.Value = ePosts.Desc.Value;
}
}
}
}
}
撰写帖子数据:
protected void Update_btn_click(object sender, EventArgs e)
{
string postid = Request.QueryString["pid"];
if (postid != null)
{
string path = "C:\\Users\\user\\Source\\Repos\\FoodBlog\\FoodBlog\\Data\\blog_post.xml";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
XDocument xdoc = XDocument.Load(fs);
var post = from p in xdoc.Descendants("post")
where (string)p.Element("pid") == postid
select new {
Title = p.Element("title"),
Subtitle = p.Element("subtitle"),
Desc = p.Element("description"),
PID = p.Element("pid")
};
foreach (var ePosts in post)
{
if (ePosts.PID.Value == postid)
ePosts.Title.ReplaceWith(newtitle.Text);
ePosts.Subtitle.ReplaceWith(Subtitle.Value);
ePosts.Desc.ReplaceWith(update_des.Value);
}
}
}
XML数据结构:
<Posts>
<post>Something<
<pid>p9119</pid>
<title>Something</title>
<description>Something</description>
<subtitle>Something</subtitle>
<date>Something</date>
<author>Something</author>
</Posts>