Solved

get xml name and value from the file in C#

Posted on 2010-08-31
9
378 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
 
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

744 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now