Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Display and Edit XML C# Web

Posted on 2011-10-24
5
Medium Priority
?
299 Views
Last Modified: 2013-11-11
Hi

I need to Display and edit an XML file on a Web portal, using C# (we also use DevExpress third party controls)

The XML is coming directly from a table field in our DB and is not a consistent format there can be differing tags and levels.

The XML data i use would be something like the format below

<TestData>
   <Value1>100</Value1>
   <Value2>100</Value2>
   <Value3>100</Value3>
   <Value4>
        <Value4_1>100</Value4_1>
   </Value4>
<TestData>

What I would like to be able to get would be something like labels (showin the tag name ie. Value1) textboxes (Showing the value ie. 100) displaying the data then a button when pressed would update the xml and store it back in the DB.

I have tried to do this in a few ways but haven't been successful so any help and advise would be greatly appreciated

Phil
0
Comment
Question by:ersldublin
  • 3
  • 2
5 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37017590
Is the entire XML structure expected to be editable, or just certain parts? If only certain parts, how would you identify those parts when modifying the original document? In database terminology, what would be the primary key of each editable part?
0
 

Author Comment

by:ersldublin
ID: 37017654
Hi

I would be looking to have the the all of the values to be editable not the Tags, so the end user could change a value from 100 to 200 if need be. As for a primary key in the structure i don't have any.  The Xml is stored in a DB table field.

cheers
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 1500 total points
ID: 37018097
Here's a *very* crude example of a route you could take. It's not a ready-for-production solution, but hopefully it should give some insight.

Markup
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_27411688._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="submit" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

Open in new window


Code-Behind
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace _27411688
{
    public partial class _Default : System.Web.UI.Page
    {
        private readonly string CONNSTRING = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        private XmlDocument data;
        private Dictionary<string, string> controlToXPathMap;

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event to initialize the page.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            controlToXPathMap = new Dictionary<string, string>();

            using (SqlConnection con = new SqlConnection(CONNSTRING))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT data FROM [SourceTable] WHERE id = 2", con))
                {
                    try
                    {
                        con.Open();
                        XmlReader reader = cmd.ExecuteXmlReader();
                        data = new XmlDocument();
                        data.Load(reader);
                    }
                    catch (SqlException)
                    {
                        Response.Write("Error querying database.");
                        Response.Flush();

                        return;
                    }
                    catch (XmlException)
                    {
                        Response.Write("Error loading XML data.");
                        Response.Flush();

                        return;
                    }
                }
            }

            CreateControlsRecursively(data.FirstChild, string.Concat("/", data.FirstChild.Name));

            base.OnInit(e);
        }

        /// <summary>
        /// Creates the dynamic controls by recursing the XmlDocument.
        /// </summary>
        /// <param name="parent">The parent.</param>
        private void CreateControlsRecursively(XmlNode parent, string xpath)
        {
            foreach (XmlNode child in parent.ChildNodes)
            {
                if (child.NodeType == XmlNodeType.Text)
                {
                    TextBox tb = new TextBox() { Text = child.InnerText };

                    this.PlaceHolder1.Controls.Add(new Label() { Text = parent.Name });
                    this.PlaceHolder1.Controls.Add(tb);
                    this.PlaceHolder1.Controls.Add(new LiteralControl() { Text = "<br />" });

                    controlToXPathMap.Add(tb.UniqueID, xpath);
                }

                CreateControlsRecursively(child, string.Concat(xpath, "/", child.Name));
            }
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            if (IsPostBack)
            {
                foreach (string key in controlToXPathMap.Keys)
                {
                    ITextControl textbox = this.PlaceHolder1.FindControl(key) as ITextControl;

                    if (textbox != null)
                    {
                        XmlNode node = data.SelectSingleNode(controlToXPathMap[key]);

                        if (node != null)
                        {
                            node.InnerText = textbox.Text;
                        }
                    }
                }

                using (SqlConnection con = new SqlConnection(CONNSTRING))
                {
                    using (SqlCommand cmd = new SqlCommand("UPDATE [SourceTable] SET data = @data WHERE id = 2", con))
                    {
                        try
                        {
                            cmd.Parameters.Add(new SqlParameter("@data", data.InnerXml));
                            con.Open();
                            cmd.ExecuteNonQuery();
                        }
                        catch (SqlException)
                        {
                            Response.Write("Error updating database.");
                            Response.Flush();

                            return;
                        }
                    }
                }
            }

            base.OnLoad(e);
        }
    }
}

Open in new window

0
 

Author Closing Comment

by:ersldublin
ID: 37031646
This was a great starting point.  Definitely helped to the right way to look at the issue.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37031819
Awesome. Glad it help  = )
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logi…
Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
Suggested Courses

579 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question