Getting Specified Node Values from Xml Document

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
XmlNode anode = xn.SelectSingleNode("ANode");
if (anode!= null)
{
string id = anode["ID"].InnerText;
string date = anode["Date"].InnerText;
XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
foreach (XmlNode node in CNodes)
{
XmlNode example = node.SelectSingleNode("Example");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
}
}

How to get specified Node values from complex XML document structure

In your xpath you need to specify you want navigate from current node (which is dot). Otherwise it would apply the xpath to the entire document.

XmlNodeList failedTestModules = testCase.SelectNodes(".//activity[@type='test-module']");

how to get the inner node and its children value of xml document in c#

You could do this, solution uses Linq to Xml.

    XDocument doc = XDocument.Load(filename);

var messages = doc.Descendants("TALLYMESSAGE").Select(s=> new {
Entry = s.Element("Entry_x0020_NO.").Value,
DATE = s.Element("DATE").Value,
GUID = s.Element("GUID").Value,
NARRATION = s.Element("NARRATION").Value,
VOTURETYPENAME = s.Element("VOTURETYPENAME").Value,
AMOUNT = s.Element("AMOUNT").Value,
NAME = s.Element("NAME").Value,

}).ToList();

Update :
As asked in comments, if you are looking to loop through each elements you could do this.

    foreach(var element in doc.Descendants("TALLYMESSAGE").Elements()) 
{
Console.WriteLine("{0} = {1}", element.Name, element.Value);
}

Check this Example

How to get node values in XML file using c#

You can try this code it may be helpful for you.

XmlDocument newdoc = new XmlDocument();
newdoc.InnerXml = " <?xml version=\"1.0\" encoding=\"utf-16\"?><HUMAN_VERIFICATION><RESPONSE_DATA><RESPONSE_STATUS><ERR>100</ERROR><MESSAGE>successful</MESSAGE></RESPONSE_STATUS><CONTACT_NUMBER>3120202456011</ CONTACT _NUMBER><PERSON_DATA><NAME>Alex</NAME><DATE_OF_BIRTH>10-9-1982</DATE_OF_BIRTH><BIRTH_PLACE>Washington</BIRTH_PLACE><EXPIRY>2020-12-15</EXPIRY></PERSON_DATA><CARD_TYPE>idcard</CARD_TYPE></RESPONSE_DATA></HUMAN_VERIFICATION>";

var selectnode = "HUMAN_VERIFICATION/RESPONSE_DATA/PERSON_DATA";
var nodes = newdoc.SelectNodes(selectnode);
foreach (XmlNode nod in nodes)
{
string name = nod["NAME" ].InnerText;
string dob = nod["DATE_OF_BIRTH"].InnerText;
string place = nod["BIRTH_PLACE" ].InnerText;
string expiry = nod["EXPIRY" ].InnerText;
Console.WriteLine("Person: {0} {1} {2} {3}", name, dob, place, expiry);
}

Find Xml Node by Node Value

You can use LINQ to XML - this will return the formatted price for a given ASIN value:

var res = XElement.Parse("data.xml")
.Descendants("ASIN").FirstOrDefault(elem => elem.Value == "12345")
.Parent.Descendants("FormattedPrice").Select(elem => elem.Value)
.FirstOrDefault();

If you want to get all ASINs in a document:

var asins = XElement.Parse("data.xml")
.Descendants("ASIN")
.Select(elem => elem.Value)
.ToList();

Edit - the problem you have arises because you omit namespaces - check LINQ to XML namespaces on msdn.

XNamespace ns = "http://webservices.amazon.com/AWSECommerceService/2011-08-01";

var res = XElement.Load("data.xml")
.Descendants(ns+ "ASIN").FirstOrDefault(elem => elem.Value == "B001MS70F2")
.Parent.Descendants(ns + "FormattedPrice").Select(elem => elem.Value)
.FirstOrDefault();

Console.WriteLine(res); // prints L10.49

Also have a look at this question on SO: XElement namespaces (How to?)

and this on msdn: https://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace(v=vs.110).aspx

How can I select a specific XML node and fetch the values in its child nodes

You could also use XDocument (Linq to XML):

string xml =@"<Settings>
<Config>
</Config>
<Items>
<Item>
<ID>Hello</ID>
<Pth>Somevalue</Pth>
<Zvb>True</Zvb>
<Ico>True</Ico>
</Item>
<Item>
<ID>Stack</ID>
<Pth>Somevalue</Pth>
<Zvb>False</Zvb>
<Ico>True</Ico>
</Item>
<Item>
<ID>Overflow</ID>
<Pth>Somevalue</Pth>
<Zvb>False</Zvb>
<Ico>True</Ico>
</Item>
</Items>
</Settings>";

XDocument xdoc = XDocument.Parse(xml);
XElement desired = xdoc.Descendants("Item").FirstOrDefault(x=>(string)x.Element("ID")=="Stack");
if(desired!=null)
{
string Pth = (string)desired.Element("Pth");
string Zvb = (string)desired.Element("Zvb");
string Ico = (string)desired.Element("Ico");
}

desired will be the wanted element.

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlFile);
XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
string Short_Fall=string.Empty;
foreach (XmlNode node in nodeList)
{
Short_Fall = node.InnerText;
}

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

How to read a specific XML node?

Try following way using Linq. Answer includes your following query also.

Also, I wanted to know how can I read other corresponding values once I get a match like the different distance values?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string uploadFilename = "dog.jpg";
XDocument xdoc = XDocument.Load(@"C:\Users\admin\XMLFile1.xml");

//// check if the xml file is having node mathcing upload filename name
List<XElement> xel = xdoc.Descendants("Name").Where(x => x.Value == uploadFilename).ToList();

if (xel.Any())
{
Console.WriteLine("I match the currently open file's name: " + uploadFilename);

//// Get list of element list's Ancestors
//// will return
////<Name>dog.jpg</Name>
////<PatternDistancesList>
//// <PatternDistance>278</PatternDistance>
//// <PatternDistance>380</PatternDistance>
////</PatternDistancesList>

//// looop through it
foreach (XElement item in xel.Ancestors("Pattern").Elements().ToList())
{

}

//// OR get another list
List<XElement> foundItems = xel.Ancestors("Pattern").Elements().ToList();
}

}
}
}

This is basic help using console application. Modify the code accordingly. Hope it helps. :)



Related Topics



Leave a reply



Submit