简体   繁体   中英

XML file to html table (loop) C#

I have the following xml file and want to parse it into an .aspx table with c#. I already have a page with aspx and cs file. I have tried this and was getting an error. Any ideas. Thank you. I also need to have each node to have a link to an html anchor where it can point to the item if possible.

XmlDocument Doc = new XmlDocument();
Doc.Load(Server.MapPath("NewsSrc.xml"));
XmlElement root = Doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("/News");
if (!IsPostBack)
{
Table tbl = new Table();
tbl.ID = "table1";
tbl.BorderWidth = 1;
this.Controls.Add(tbl);

foreach (XmlNode node in nodes)
{
TableRow rw = new TableRow();
TableCell cell = new TableCell();
var element = (XmlElement)node;
var Title = element.Value; //["Title"];
NewsItemTxt.Text = Title; //NewsItemtxt is label;
cell.Controls.Add(NewsItemTxt);
rw.Cells.Add(cell);
tbl.Controls.Add(rw); 
}
}

// and the xml file is //

<?xml version="1.0" encoding="utf-8" ?>
<!-- Edited by myself  -->
<News>
<NewsItem id="1">
<Title> news tile one </Title>
<Summary> this is summary to show ....</Summary>
<Details>details for this news</Details>
</NewsItem>

<NewsItem id="2">
<Title>test title </Title>
<Summary>sm line</Summary>
<Details> no details</Details>
</NewsItem>
</News>

A simple sample to convert xml to html (table). You can use class css named 'xmlTable' to format the table created.

void Main()
{
    string s = File.ReadAllText(@"C:\Temp\Scratch\Test.xml");
    string p = ConvertXmlToHtml(s);
    File.WriteAllText(@"C:\Temp\Scratch\Test.html",p);
        
}

protected string ConvertXmlToHtml(string xml)
{
    StringBuilder html = new StringBuilder("<html><body><table align='center' " +
       "border='1' class='xmlTable'>\r\n");
    try
    {
        XDocument xDocument = XDocument.Parse(xml);
        XElement root = xDocument.Root;

        var xmlAttributeCollection = root.Elements().Attributes();


        foreach (var ele in root.Elements())
        {
            if (!ele.HasElements)
            {
                string elename = "";
                html.Append("<tr>");

                elename = ele.Name.ToString();

                if (ele.HasAttributes)
                {
                    IEnumerable<XAttribute> attribs = ele.Attributes();
                    foreach (XAttribute attrib in attribs)
                        elename += Environment.NewLine + attrib.Name.ToString() +
                          "=" + attrib.Value.ToString();
                }

                html.Append("<td>" + elename + "</td>");
                html.Append("<td>" + ele.Value + "</td>");
                html.Append("</tr>");
            }
            else
            {
                string elename = "";
                html.Append("<tr>");

                elename = ele.Name.ToString();

                if (ele.HasAttributes)
                {
                    IEnumerable<XAttribute> attribs = ele.Attributes();
                    foreach (XAttribute attrib in attribs)
                        elename += Environment.NewLine + attrib.Name.ToString() + "=" + attrib.Value.ToString();
                }

                html.Append("<td>" + elename + "</td>");
                html.Append("<td>" + ConvertXmlToHtml(ele.ToString()) + "</td>");
                html.Append("</tr>");
            }
        }

        html.Append("</table>");
        html.Append("</body></html>");
    }
    catch (Exception e)
    {
        return xml;
    }
    
    return html.ToString();
}

This answer assumes we are talking about an ASP.NET solution:

Perhaps you should look at some tutorials on using an XmlDataSource . Once your datasource is configured you could bind to a GridView/DataList control (or Repeater if you want more fine-grained control of the control output).

Until we know the error, here's a shot in the dark:

If the NodeType of that node is "Element" (from a brief glance at the docs, it seems likely that's what the <Title> tag would be considered), its Value property will be null. As per MSDN :

You can use the XmlElement.InnerText or XmlElement.InnerXml properties to access the value of the element node.

See if that fixes it. Again, my best guess given we've no idea what's actually wrong.

Try this, it's using System.Xml and System.Xml.Linq, it should work but I can't guarantee it:

var xmlDoc = XDocument.Load(new XmlTextReader(Server.MapPath("NewsSrc.xml")));
foreach(var descendant in xmlDoc.Descendants("NewsItem"))
{
   var title = descendant.Element("Title").Value;
   var summary = descendant.Element("Summary").Value;
   var details = descendant.Element("Details").Value;
   var id = descendant.Attribute("id").Value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM