Link to home
Start Free TrialLog in
Avatar of Ellos Lai
Ellos Lai

asked on

Failed to read values from XML

Hi, I am new to ASP.net programming. Fyi, I am trying to read title data(xml data) from my response query string(working), however, I couldn't retrieve any data from my code.

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"];
            
                        

            string filename = "C:\\Users\\user\\Source\\Repos\\FoodBlog\\FoodBlog\\Data\\blog_post.xml";
            XmlDocument xml_doc = new XmlDocument();
            XmlNode elemList = xml_doc.SelectSingleNode("/Posts/Post[@pid=" + postid + "]");
            String test = elemList.ChildNodes[0].Innertext;
            System.Diagnostics.Debug.WriteLine(test);
}

Open in new window


My XML data :
<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>

Open in new window

Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi Ellos Lai;
 
You need to load the XML from the file system after creating the XML document and before using it as shown below.
XmlDocument xml_doc = new XmlDocument();
// Load the XML in to the XML document object.
xml_doc.Load(filename);
XmlNode elemList = xml_doc.SelectSingleNode("/Posts/Post[@pid=" + postid + "]");

Open in new window

Avatar of Ellos Lai
Ellos Lai

ASKER

Hi sir , I have added the required code as you suggested but right now it is throwing an exception :

Exception thrown: 'System.Threading.ThreadAbortException' in mscorlib.dll

I am sending a redirect query from my XSLT file :

<td><a class="btn btn-default" href="EditPost.aspx?pid={@pid}">Edit</a> <a class="btn btn-danger" href="#">Delete</a></td>

Open in new window


And a web form will be accepting the query and read the correct data :

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"];
            string docPath = @"~/Data/blog_post.xml";

             XmlDocument xml_doc = new XmlDocument();

            xml_doc.Load(Server.MapPath(docPath));
            
            XmlNode elemList = xml_doc.SelectSingleNode("/Posts/post[@pid=" + postid + "]/title");
            System.Diagnostics.Debug.WriteLine(elemList);
        }

Open in new window


My XML data :
<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>

Open in new window

You missed to load the actual file.. also XML and XPath are case-sensitve, thus you need /Posts/post as path expression. And the filter condition requires quotes. I would use XDocument or the built-in XML serializer + LINQ, e.g.

namespace ConsoleCS
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Xml.Linq;
    using System.Xml.Serialization;
    using System.Xml.XPath;

    [XmlRoot("Posts")]
    public class PostsContainer
    {
        [XmlElement("post")]
        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        [XmlAttribute("pid")]
        public string ID { get; set; }
        [XmlElement("title")]
        public string Title { get; set; }
        [XmlElement("description")]
        public string Description { get; set; }
        [XmlElement("subtitle")]
        public string Subtitle { get; set; }
        [XmlElement("date")]
        public string Date { get; set; }
        [XmlElement("author")]
        public string Author { get; set; }
        public override string ToString()
        {
            return $"{this.ID}: {this.Title} / {this.Date}";
        }
    }

    public static class EnumHelper
    {
        public static void ToConsole<T>(this IEnumerable<T> @this)
        {
            foreach (T item in @this)
            {
                Console.WriteLine(item);
            }
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            string filename = @"c:\Temp\test.xml";
            string postid = "pid2623";
            XElement post = LoadPost(filename, postid);
            Console.WriteLine(post);

            PostsContainer container = LoadPostContainer(filename);
            container.Posts
                .Where(p => p.ID.Equals(postid))
                .ToConsole<Post>();

            Console.WriteLine("Done.");
            Console.ReadLine();
        }

        private static PostsContainer LoadPostContainer(string filename)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(PostsContainer));
            using (TextReader reader = new StreamReader(filename))
            {
                return (PostsContainer)serializer.Deserialize(reader);
            }
        }

        private static XElement LoadPost(string filename, string postid)
        {
            XDocument document = XDocument.Load(filename);
            XElement post = document.XPathSelectElement("/Posts/post[@pid='" + postid + "']");
            return post;
        }
    }
}

Open in new window


p.s. your date literal in XML is not a valid XML date. Use YYYY-MM-DDThh:mm:ss then you can easily convert it to DateTime in C#.
@ste5an

Thank you for the hint,  I have loaded the XML file but an exception is throwing. Fyi, I have tried my best to come to this far, and this error is out of my league. My previous comment explains the problem.
Really appreciate your help.
Clean up your code (separation of concerns):

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"];
    string docPath = @"~/Data/blog_post.xml";
    XmlNode elemList = LoadPost(postid, Server.MapPath(docPath));    
}

private static XmlNode LoadPost(string postid, string file)
{
    if (!File.Exists(file))
    {
        throw new ArgumentException($"File {file} not found.");
    }

    XmlNode result;
    try
    {
        XmlDocument document = new XmlDocument();
        document.Load(file);
        result = document.SelectSingleNode("/Posts/post[@pid=" + postid + "]");
        System.Diagnostics.Debug.WriteLine(result);
    }
    catch(Exception exception)
    {
        // handle exception
        throw;
    }
}

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.