yonan2236
yonan2236

Reputation: 13649

How to get the value from XML?

I'm making a small tool for checking the material number from the XML file.

I know this quite easy for you experts and I would like to ask for your help on this to get me started on this. On my machine I have .NET 2.0 framework I guess, and VS C# Express 2005 installed.

I have an XML that contains data of a material. It is located at my local drive. I am able now to browse the XML file and save the file in a string variable. Well, that's what I have done so far..

if(folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
    string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "Product.xml");

    string prodFile = files[0];
    ...
    ...

Suppose this is the structure of the XML:

<Record>
    <Product>
        <Material_Number>20209485</Material_Number> 
        <Product_Type>Type1</Product_Type>
        ...
        ...
    </Product>
</Record>

How can I get the material number value?

Upvotes: 3

Views: 204

Answers (3)

jfiskvik
jfiskvik

Reputation: 645

You could also use XPathNavigator and XPathExpression with XmlDocument.

var xmlDoc = new XmlDocument();
xmlDoc.Load("Product.xml") //or xmlDoc.LoadXml(xmlString);
var xmlNav = xmlDoc.CreateNavigator();
string materialNum;
var iterator = xmlNav.Select("/Record/Product/Material_Number");
if (iterator.MoveNext() && iterator.Current != null)
    materialNum = iterator.Current.Value;

If you use .Net 3.0+ you could use System.Xml.Linq.XDocument.

var xdoc = XDocument.Load("Product.xml"); //or var xdoc = XDocument.Parse(xmlString);
var materialNum = xdoc.Root.Element("Product").Element("Material_Number").Value;

Upvotes: 1

yonan2236
yonan2236

Reputation: 13649

I was able to find a solution. Not so elegant though...

XmlDocument xmlDoc= new XmlDocument(); 
xmlDoc.Load(@"C:\Product.xml");                 

XmlNodeList a = xmlDoc.GetElementsByTagName("Material_Number"); 
string materialNumber = a[0].InnerText;

Upvotes: 0

dknaack
dknaack

Reputation: 60468

You can use the XmlDocument class for loading your XML File into a DOM.

MSDN - This class implements the W3C Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. The DOM is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document. Because XmlDocument implements the IXPathNavigable interface it can also be used as the source document for the XslTransform class.

Sample

There are many ways to read your value. I really encourage you to read Working with Xml DOM

XmlNodeList list = xml.GetElementsByTagName("Product");
XmlAttributeCollection attr = list[0].Attributes;
string materialNumber = list[0].ChildNodes[0].InnerText;

or

XmlNodeList list  = xml.GetElementsByTagName("Material_Number"); 
string materialNumber = list[0].InnerText;

More Information

Upvotes: 3

Related Questions