Solved

get xml name and value from the file in C#

Posted on 2010-08-31
9
395 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
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

Is Your Team Achieving Their Full Potential?

74% of employees feel they are not achieving their full potential. With Linux Academy, not only will you strengthen your team's core competencies but also their knowledge of of the newest IT topics.

With new material every week, we'll make sure that you stay ahead of the game.

Question has a verified solution.

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

I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Create a Windows 10 custom Image with custom task bar and custom start menu using XML for deployment.
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

623 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