Solved

get xml name and value from the file in C#

Posted on 2010-08-31
9
389 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 20 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 20 total points
ID: 33568853
DataSet ds = new DataSet();

ds.ReadXml(stream);

and then execute the queries to get the required values
0
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 
LVL 3

Accepted Solution

by:
GoJoeIsBlue earned 460 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

821 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