开发者

xml attributes from SQL in C#

C# winform: I asked a similar Q but didn't reached to the solution so i want to make it more clear, I have a string let suppose

str = "<sample>
    <sample1 name="val1">
        <sample2 name="val2">
        </sample2>
        <sample2 name="val3">
            <groupbox name="va开发者_开发问答l4">
            <field type="textArea" x="xxx" />
            </groupbox>
        </sample2>
    </sample1>
    <sample1 name="abc">
    </sample1>
    <sample1 name="xyz">
    </sample1>
</sample>"

i want to get the attributes and thier values from this string and place it in gridView notice that this string is just an example it could be changed. or display in any control like richTextField .... etc


I've given this solution before - this code will parse your one XML string and it will return the list of attributes and their values - so what else / what more do you need??

private static List<KeyValuePair<string, string>> ParseForAttributeNames(string xmlContent)
{
    List<KeyValuePair<string, string>> attributeNamesAndValues = new List<KeyValuePair<string, string>>();

    XDocument xmlDoc = XDocument.Parse(xmlContent);

    var nodeAttrs = xmlDoc.Descendants().Select(x => x.Attributes());

    foreach (var attrs in nodeAttrs)
    {
        foreach (var attr in attrs)
        {
           string attributeName = attr.Name.LocalName;
           string attributeValue = attr.Value;

           attributeNamesAndValues.Add(new KeyValuePair<string, string>(attributeName, attributeValue));
        }
     }

     return attributeNamesAndValues;
  }

If you can explain in good, comprehensible English what else you need, I might make the effort to answer you once again with even more info.... but you need to be clear and precise about what it is you need - otherwise me as an illiterate idiot won't be able to answer......


try this:

StringReader rdr = new StringReader(str);

        DataSet ds = new DataSet();

        ds.ReadXml(str);
        DataTable dt = ds.Tables[0];
        datagridview.datasource = dt;


For your other question that keeps coming up over and over again (grabbing XML attributes from SQL Server) - this is a complete sample that will

  • read all rows from a table and extract all the XML columns
  • parse all the XML contents into a list of attribute name/values
  • return a bindable list of attribute name/value pairs, which you can bind to a ListView, a GridView - whatever you like.

Please check it out - and if it doesn't meet your needs, please explain in comprehensible English what it is that's still missing.....

using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Xml.Linq;

namespace GrabAndParseXml
{
    internal class AttrNameAndValue
    {
        public string AttrName { get; set; }
        public string AttrValue { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // grab *ALL* the "XmlContent" columns from your database table
            List<string> xmlContent = GrabXmlStringsFromDatabase();

            // parse *ALL* your xml strings into a list of attribute name/values
            List<AttrNameAndValue> attributeNamesAndValues = ParseForAttributeNamesAndValues(xmlContent);

            // you can now easily bind this list of attribute names and values to a ListView, a GridView - whatever - try it!
        }

        private static List<string> GrabXmlStringsFromDatabase()
        {
            List<string> results = new List<string>();

            // connection string - adapt to **YOUR SETUP** !
            string connection = "server=(local);database=test;integrated security=SSPI";

            // Query to get the XmlContent columns - I would **ALWAYS** recommend to have a WHERE clause 
            // to limit the number of rows returned from the query - up to you....
            string query = "SELECT XmlContent FROM dbo.TestXml WHERE 1=1";

            // set up connection and command for data retrieval
            using(SqlConnection _con = new SqlConnection(connection))
            using (SqlCommand _cmd = new SqlCommand(query, _con))
            {
                _con.Open();

                // use a SqlDataReader to loop over the results
                using(SqlDataReader rdr = _cmd.ExecuteReader())
                {
                    while(rdr.Read())
                    {
                        // stick all XML strings into resulting list
                        results.Add(rdr.GetString(0));
                    }

                    rdr.Close();
                }

                _con.Close();
            }

            return results;
        }

        private static List<AttrNameAndValue> ParseForAttributeNamesAndValues(List<string> xmlContents)
        {
            // create resulting list of "AttrNameAndValue" objects
            List<AttrNameAndValue> attributeNamesAndValues = new List<AttrNameAndValue>();

            // loop over all XML strings retrieved from the database
            foreach (string xmlContent in xmlContents)
            {
                // parse into an XDocument (Linq-to-XML)
                XDocument xmlDoc = XDocument.Parse(xmlContent);

                // find **ALL** attribute nodes
                var nodeAttrs = xmlDoc.Descendants().Select(x => x.Attributes());

                // loop over **ALL** atributes in each attribute node
                foreach (var attrs in nodeAttrs)
                {
                    foreach (var attr in attrs)
                    {
                        // stick name and value into the resulting list
                        attributeNamesAndValues.Add(new AttrNameAndValue { AttrName = attr.Name.LocalName, AttrValue = attr.Value });
                    }
                }
            }

            return attributeNamesAndValues;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜