Displaying / editing xml in an MVC app

2020-07-17 08:06发布

问题:

I need to maintain an xml column in a SQL database.

a) in my details page - I just want to display this column as "pretty" xml - like the browser would. So instead of one big block of xml (e.g. <foo><bar><data>one</data><data>two</data><data>three</data></bar><other>something else></other></foo> ) I want it split out with each new tag on a new line (e.g.

<foo>
  <bar>
    <data>one</data>
    <data>two</data>
    <data>three</data>
  </bar>
  <other>something else></other>
</foo>

and

b) in my edit page I want a simple form with the tags as headings (in bold for instance) and the node values as editable text boxes - but I want this to be created dynamically from the xml itself. I don't want to hard-code the tag labels in my code, but loop through the xml and fetch them on the fly.

I'm using c# .net for my MVC application with Sql Server as the database and LINQ to SQL.

回答1:

For your first question you can put the XML string in a XDocument.

XDocument doc = XDocument.Parse("<foo><bar><data>one</data><data>two</data><data>three</data></bar><other>something else></other></foo>");

ViewData["XmlData"] = doc.ToString();

Now in your view present the value of ViewData["XmlData"] in a <pre><code> HTML element.