简体   繁体   中英

Parse xml from database

Currently I have xml stored in a ms sql dbase and not a file . Here's a small sample.

<NewDataSet>
<Table1>
<billTo_lastName>asdf</billTo_lastName>
<orderAmount>160.00</orderAmount>
<billTo_street1>asdf</billTo_street1>
<card_accountNumber>############1111</card_accountNumber>
</Table1>
</NewDataSet>

Currently I'm returning the result in a Datable .

What would be the best way to parse the above and display it on a page. The page display is just for informational review. No additional processing will be done to the xml.

I would like the page to display something along these lines.

billTo_lastName: asdf
orderAmount: 160.00
etc.

Depends on how you want to process it. One way is to create an XmlDocument and then call LoadXml :

// get the data from the data table, into a string.

// then create an XML document and load the string
var doc = new XmlDocument();
doc.LoadXml(dataString);

If you want to use Linq-to-Xml, you'd create an XElement :

var element = XElement.Load(dataString);

Thanks to Jim for pointing me in the right direction. XmlDocuments LoadXml works just fine. I then was able to put that into an XmlNodeList and selected the top node. Did XmlNode and looped through the child nodes.

    DataTable dt = sqlselect(sqlQuery, parameter);
    var doc = new XmlDocument();
    doc.LoadXml(dt.Rows[0]["ua_post"].ToString());

    XmlNodeList nl = doc.SelectNodes("NewDataSet");
    XmlNode root = nl[0];

    foreach (XmlNode xnode in root.ChildNodes[0])
    {
        string name = xnode.Name;
        string value = xnode.InnerText;
        string nv = "<b>" + name + ":</b> " + value;
        Label1.Text += nv + " <br />" + Environment.NewLine;
    }

And I get a simple display on a page.

    billTo_lastName: asdf 
    orderAmount: 160.00 
    billTo_street1: asdf 
    card_accountNumber: ############1111 

You can return them as columns from Database into DataTable and then display them using any datacontrol with ItemTemplates For example:

declare @xml as xml
set @xml = '<NewDataSet>
<Table1>
<billTo_lastName>asdf</billTo_lastName>
<orderAmount>160.00</orderAmount>
<billTo_street1>asdf</billTo_street1>
<card_accountNumber>############1111</card_accountNumber>
</Table1>
</NewDataSet>'

;with cte as (    
  select @xml xmlstring
)
SELECT 
xmlstring.value('(/NewDataSet//Table1/billTo_lastName/node())[1]','VARCHAR(100)')
 as billTo_lastName,
xmlstring.value('(/NewDataSet//Table1/orderAmount/node())[1]','VARCHAR(20)') 
as orderAmount
FROM cte

SQL DEMO

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