Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

get xml name and value from the file in C#

Posted on 2010-08-31
9
Medium Priority
?
397 Views
Last Modified: 2012-05-10
I have an xml file with the following format:

<?xml version="1.0" ?>
- <root>
  <SalesPartNoIndex>0</SalesPartNoIndex>
  <SalesPartDescriptionIndex>1</SalesPartDescriptionIndex>
  <CustomerIDIndex>2</CustomerIDIndex>
  <BasePriceIndex>3</BasePriceIndex>
  <SalesPriceIndex>4</SalesPriceIndex>
  <NetPriceIndex>5</NetPriceIndex>
  <QuantityAvlIndex>6</QuantityAvlIndex>
  <PlannableQtyIndex>7</PlannableQtyIndex>
  <StatusIndex>8</StatusIndex>
  <DiscountTypeIndex>10</DiscountTypeIndex>
  <DiscountPercIndex>11</DiscountPercIndex>
  <SubstPartIndex>12</SubstPartIndex>
  <AuthorizedIndex>13</AuthorizedIndex>
  <CatalogTypeIndex>14</CatalogTypeIndex>
  <ProductFamIndex>15</ProductFamIndex>
  <ProductGrpIndex>16</ProductGrpIndex>
  <ReservationCtrlIndex>17</ReservationCtrlIndex>
  <SalesPartNoWidth>100</SalesPartNoWidth>
  <SalesPartDescriptionWidth>100</SalesPartDescriptionWidth>
  <CustomerIDWidth>100</CustomerIDWidth>
  <BasePriceWidth>100</BasePriceWidth>
  <SalesPriceWidth>100</SalesPriceWidth>
  <NetPriceWidth>100</NetPriceWidth>
  <QuantityAvlWidth>100</QuantityAvlWidth>
  <PlannableQtyWidth>100</PlannableQtyWidth>
  <StatusWidth>100</StatusWidth>
  <DiscountTypeWidth>100</DiscountTypeWidth>
  <DiscountPercWidth>100</DiscountPercWidth>
  <SubstPartWidth>100</SubstPartWidth>
  <AuthorizedWidth>100</AuthorizedWidth>
  <CatalogTypeWidth>100</CatalogTypeWidth>
  <ProductFamWidth>100</ProductFamWidth>
  <ProductGrpWidth>100</ProductGrpWidth>
  <ReservationCtrlWidth>100</ReservationCtrlWidth>
  <SATPWidth>100</SATPWidth>
  <SATPDescriptionWidth>100</SATPDescriptionWidth>
  <CatalogCodeWidth>100</CatalogCodeWidth>
  <SATPIndex>18</SATPIndex>
  <SATPDescriptionIndex>19</SATPDescriptionIndex>
  <CatalogCodeIndex>20</CatalogCodeIndex>
  </root>

I am trying to read each name and get its value
for example
<SATPDescriptionIndex>19</SATPDescriptionIndex>

name = SATPDescriptionIndex
value =19
columnname = SATPDescription
columntype = Index

  <SATPDescriptionWidth>100</SATPDescriptionWidth>

name = SATPDescriptionWidth
value =100
columnname = SATPDescription
columntype = Width

I am trying to place these values into a Dictionary

if (columntype == "Width")
{ WidthDictionary.Add(columnname,value); }

if (columntype == "Index")
{ IndexDictionary.Add(columnname,value); }

thanks
0
Comment
Question by:jhacharya
9 Comments
 
LVL 9

Assisted Solution

by:puru1981
puru1981 earned 80 total points
ID: 33567661
you can use a dataset to load the xml.

you will find the a datatable.

from there you can use getschema to find the fieldNames.

then after iterating through rows you can get the values of the each column.
0
 
LVL 2

Author Comment

by:jhacharya
ID: 33567779
could you give me a sample procedure?
0
 
LVL 8

Assisted Solution

by:Gururaj Badam
Gururaj Badam earned 80 total points
ID: 33568853
DataSet ds = new DataSet();

ds.ReadXml(stream);

and then execute the queries to get the required values
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Accepted Solution

by:
GoJoeIsBlue earned 1840 total points
ID: 33568857
You could do this with Linq:

using System.Text.RegularExpressions;

Regex postfixExpression = new Regex("(.*)(index|width)$", RegexOptions.IgnoreCase);
// Get all in one collection
var resultAllInOne = from x in XDocument.Parse(myxml).Root.Elements()
 select new
 {
	Name = x.Name.LocalName,
	Value = x.Value,
	ColumnType = x.Name.LocalName.EndsWith("index", StringComparison.OrdinalIgnoreCase)? "Index" : "Width",
	ColumnName = postfixExpression.Replace(x.Name.LocalName, "$1")
 };

// Retrieve only Index items
var resultIndexItems = from x in XDocument.Parse(myxml).Root.Elements()
 where x.Name.LocalName.EndsWith("index", StringComparison.OrdinalIgnoreCase)
 select new
 {
	Name = x.Name.LocalName,
	Value = x.Value,
	ColumnType = "Index",
	ColumnName = postfixExpression.Replace(x.Name.LocalName, "$1")
 };

// Retrieve only Width items
var resultWidthItems = from x in XDocument.Parse(myxml).Root.Elements()
 where x.Name.LocalName.EndsWith("width", StringComparison.OrdinalIgnoreCase)
 select new
 {
	Name = x.Name.LocalName,
	Value = x.Value,
	ColumnType = "Width",
	ColumnName = postfixExpression.Replace(x.Name.LocalName, "$1")
 };

Open in new window

0
 
LVL 2

Author Comment

by:jhacharya
ID: 33577223
hi GoJoe

I am having an issue trying to compile the code, what DLL do I need to use XDocumnet and myxml

on the code line shown below both Xdocument and myxml do not exist..

var resultAllInOne = from x in XDocument.Parse(myxml).Root.Elements()


0
 
LVL 2

Author Comment

by:jhacharya
ID: 33577277
ok found the library its system.xml.linq

any myxml is the xml file that i want to parse  right? so the datatype of myxml should be System.Xml.XmlDocument

is that right?
0
 
LVL 2

Author Comment

by:jhacharya
ID: 33577758
the var resultALLInOne isthe collection, but how do i pass the collection back?

for example

public ???? testXml(System.Xml.XmlDocument lv_XMLDoc )

            Regex postfixExpression = new Regex("(.*)(index|width)$", RegexOptions.IgnoreCase);
            // Get all in one collection
            var resultAllInOne = from x in XDocument.Parse(lv_XMLDoc).Root.Elements()
             select new
             {
                  Name = x.Name.LocalName,
                  Value = x.Value,
                  ColumnType = x.Name.LocalName.EndsWith("index", StringComparison.OrdinalIgnoreCase)? "Index" : "Width",
                  ColumnName = postfixExpression.Replace(x.Name.LocalName, "$1")
             };
    }

need a bit of help

So the idea would be pass the xml document to this procedure,

i would use

        public System.Xml.XmlDocument LoadXMLDoc(string XMLfile_directory
                            , string XMLfilename)
        {
            System.Xml.XmlDocument XMLDoc = new XmlDocument();

            //Set up the filestream (READER) //
            FileStream XMLFile = new FileStream
                            (XMLfile_directory + XMLfilename
                            , FileMode.Open
                            , FileAccess.Read
                            , FileShare.ReadWrite);

            //Load the data from the file into the XMLDOC//
            XMLDoc.Load(XMLFile);

            return XMLDoc;

        } //public void LoadXMLDoc

to load the file into and XML variable and then try to use the procedure you gave to put the values into a collection. and then pass the collection to the calling procedure
0
 
LVL 2

Author Comment

by:jhacharya
ID: 33580231
ok made the corrections and here is a working solution


        public string GetXmlString(XmlDocument xmlDoc)
        {
            StringWriter sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);
            xmlDoc.WriteTo(xw);
            return sw.ToString();
        }

        public Dictionary<string, string> XmlIndexWidth(XmlDocument lv_XMLDoc)
        {
            string XMLStr = GetXmlString(lv_XMLDoc);
            Dictionary<string, string> ReturnDictionary = new Dictionary<string,string>();

            Regex postfixExpression = new Regex("(.*)(index|width)$", RegexOptions.IgnoreCase);
            // Get all in one collection
            var resultAllInOne = from x in XDocument.Parse(XMLStr).Root.Elements()
             select new
             {
                  Name = x.Name.LocalName,
                  Value = x.Value,
                  ColumnType = x.Name.LocalName.EndsWith("index", StringComparison.OrdinalIgnoreCase)? "Index" : "Width",
                  ColumnName = postfixExpression.Replace(x.Name.LocalName, "$1")
             };

            foreach (var x in resultAllInOne)
            {ReturnDictionary.Add(x.Name, x.Value);}

            return ReturnDictionary;
        } //public Dictionary<string, string> XmlIndexWidth(XmlDocument lv_XMLDoc)

        public Dictionary<string, string> XmlIndex(XmlDocument lv_XMLDoc)
        {
            string XMLStr = GetXmlString(lv_XMLDoc);
            Dictionary<string, string> ReturnDictionary = new Dictionary<string, string>();

            Regex postfixExpression = new Regex("(.*)(index|width)$", RegexOptions.IgnoreCase);
            // Retrieve only Index items
            var resultIndexItems = from x in XDocument.Parse(XMLStr).Root.Elements()
                                   where x.Name.LocalName.EndsWith("index", StringComparison.OrdinalIgnoreCase)
                                   select new
                                   {
                                       Name = x.Name.LocalName,
                                       Value = x.Value,
                                       ColumnType = "Index",
                                       ColumnName = postfixExpression.Replace(x.Name.LocalName, "$1")
                                   };

            foreach (var x in resultIndexItems)
            { ReturnDictionary.Add(x.ColumnName, x.Value); }

            return ReturnDictionary;
        }//public Dictionary<string, string> XmlIndex(XmlDocument lv_XMLDoc)

        public Dictionary<string, string> XmlWidth(XmlDocument lv_XMLDoc)
        {
            string XMLStr = GetXmlString(lv_XMLDoc);
            Dictionary<string, string> ReturnDictionary = new Dictionary<string, string>();

            Regex postfixExpression = new Regex("(.*)(index|width)$", RegexOptions.IgnoreCase);
            // Retrieve only Width items
            var resultWidthItems = from x in XDocument.Parse(XMLStr).Root.Elements()
                                   where x.Name.LocalName.EndsWith("width", StringComparison.OrdinalIgnoreCase)
                                   select new
                                   {
                                       Name = x.Name.LocalName,
                                       Value = x.Value,
                                       ColumnType = "Width",
                                       ColumnName = postfixExpression.Replace(x.Name.LocalName, "$1")
                                   };


            foreach (var x in resultWidthItems)
            { ReturnDictionary.Add(x.ColumnName, x.Value); }

            return ReturnDictionary;
        }//public Dictionary<string, string> XmlWidth(XmlDocument lv_XMLDoc)
0
 
LVL 2

Author Closing Comment

by:jhacharya
ID: 33580254
I had to make a few chnages but the solution provided by Jo was far the beast and easy to follow for a novice like myself
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

782 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