How to parse all the XML files under a given directory as an input to the application and write its output to a text file.
Note: The XML is not always the same the nodes in the XML can vary and have any number of Child-nodes.
Any help or guidance would be really helpful on this regard :)
XML File Sample
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>
<CNT>USA</CNT>
<CODE>3456</CODE>
</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>
C# Code
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace XMLTagParser
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter the Location of the file");
// get the location we want to get the sitemaps from
string dirLoc = Console.ReadLine();
// get all the sitemaps
string[] sitemaps = Directory.GetFiles(dirLoc);
StreamWriter sw = new StreamWriter(Application.StartupPath + #"\locs.txt", true);
// loop through each file
foreach (string sitemap in sitemaps)
{
try
{
// new xdoc instance
XmlDocument xDoc = new XmlDocument();
//load up the xml from the location
xDoc.Load(sitemap);
// cycle through each child noed
foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
{
// first node is the url ... have to go to nexted loc node
foreach (XmlNode locNode in node)
{
string loc = locNode.Name;
// write it to the console so you can see its working
Console.WriteLine(loc + Environment.NewLine);
// write it to the file
sw.Write(loc + Environment.NewLine);
}
}
}
catch {
Console.WriteLine("Error :-(");
}
}
Console.WriteLine("All Done :-)");
Console.ReadLine();
}
}
}
Preferred Output:
CATALOG/CD/TITLE
CATALOG/CD/ARTIST
CATALOG/CD/COUNTRY/CNT
CATALOG/CD/COUNTRY/CODE
CATALOG/CD/COMPANY
CATALOG/CD/PRICE
CATALOG/CD/YEAR
CATALOG/CD/TITLE
CATALOG/CD/ARTIST
CATALOG/CD/COUNTRY
CATALOG/CD/COMPANY
CATALOG/CD/PRICE
CATALOG/CD/YEAR
This is a recursive problem, and what you are looking for is called 'tree traversal'. What this means is that for each child node, you want to look into it's children, then into that node's children (if it has any) and so on, recording the 'path' as you go along, but only printing out the names of the 'leaf' nodes.
You will need a function like this to 'traverse' the tree:
static void traverse(XmlNodeList nodes, string parentPath)
{
foreach (XmlNode node in nodes)
{
string thisPath = parentPath;
if (node.NodeType != XmlNodeType.Text)
{
//Prevent adding "#text" at the end of every chain
thisPath += "/" + node.Name;
}
if (!node.HasChildNodes)
{
//Only print out this path if it is at the end of a chain
Console.WriteLine(thisPath);
}
//Look into the child nodes using this function recursively
traverse(node.ChildNodes, thisPath);
}
}
And then here is how I would add it into your program (within your foreach sitemap loop):
try
{
// new xdoc instance
XmlDocument xDoc = new XmlDocument();
//load up the xml from the location
xDoc.Load(sitemap);
// start traversing from the children of the root node
var rootNode = xDoc.FirstChild;
traverse(rootNode.ChildNodes, rootNode.Name);
}
catch
{
Console.WriteLine("Error :-(");
}
I made use of this other helpful answer: Traverse a XML using Recursive function
Hope this helps! :)
Related
I am trying to display the id attribute of the channel element called id, the inner text of the display-name tag and the inner text of the icon that sometimes is contained inside the channel element.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tv SYSTEM "xmltv.dtd">
<tv generator-info-name="xmltv.co.uk" source-info-name="xmltv.co.uk">
<channel id="0052a71acac348ff93f5680aa9c125eb">
<display-name>2910</display-name>
</channel>
<channel id="00da025711e82cf319cb488d5988c099">
<display-name>Sony Movies</display-name>
</channel>
<channel id="00dfea977320f17bb419abaa1f079f39">
<display-name>Good Food</display-name>
<icon src="/images/channels/00dfea977320f17bb419abaa1f079f39.png"/>
</channel>
<channel id="018202232e044b504f9dc5263617d496">
<display-name>The Box</display-name>
<icon src="/images/channels/018202232e044b504f9dc5263617d496.png"/>
</channel>
I tried using this code C# code below But the second if give me a error about not referenced to an object.
XmlDocument doc = new XmlDocument();
doc.Load(xmlLocation);
//dispaly the nodes
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
//get the channel
if (node.Name.Equals("channel"))
{
Debug.WriteLine("Channel Name : " + node.ChildNodes[0].Name.ToString()); //or loop through its children as well
//Debug.WriteLine("Channel Name : " + node.AttributeCount.ToString()); //or loop through its children as well
//get the icon element
if(node.ChildNodes[1].Name != null)
Debug.WriteLine("Channel Name : " + node.ChildNodes[1].Name.ToString());
}
}
Although XDocument/XElement and LinQ to XML is the new trend,
to follow your implementation, and adding to it only one feature (using XPATH to query document contents);
Please find the code to fetch channel names and their respective icon source URL's (if exist)
By applying SelectNodes and SelectSingleNode, the API is iterating over the nodes for us.
// Select all the XML elements whose name is "channel"
foreach (XmlNode channelNode in doc.DocumentElement.SelectNodes("channel"))
{
// check if a child element with the name "display-name" exists
XmlNode displayNameNode = channelNode.SelectSingleNode("display-name");
if (displayNameNode != null)
{
// If yes, print the inner text
Debug.WriteLine("Channel Name : " + displayNameNode.InnerText);
}
// then check if the icon node exists
XmlNode iconNode = channelNode.SelectSingleNode("icon");
if (iconNode != null)
{
// and check if it has an attribute with the name "src"
if (iconNode.Attributes["src"] != null)
{
// and if yes, print out its value
Debug.WriteLine(" Icon Src : " + iconNode.Attributes["src"].Value);
}
}
}
First, you need to convert string to XML and load them up in XmlDocument and then use the XPath as shown below. The simple program you can run that in dotnetfiddle.net to check this out.
using System;
using System.Xml;
public class Program
{
public static void Main()
{
string xmlString = "<tv generator-info-name='xmltv.co.uk' source-info-name='xmltv.co.uk'> <channel id='0052a71acac348ff93f5680aa9c125eb'> <display-name>2910</display-name> </channel> <channel id='00da025711e82cf319cb488d5988c099'> <display-name>Sony Movies</display-name> </channel> <channel id='00dfea977320f17bb419abaa1f079f39'> <display-name>Good Food</display-name> <icon src='/images/channels/00dfea977320f17bb419abaa1f079f39.png'/> </channel> <channel id='018202232e044b504f9dc5263617d496'> <display-name>The Box</display-name> <icon src='/images/channels/018202232e044b504f9dc5263617d496.png'/> </channel></tv>";
XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(xmlString);
XmlNodeList itemNodes = xmltest.SelectNodes("//tv/channel");
foreach(XmlNode itemNode in itemNodes)
{
if (itemNode!= null) {
Console.WriteLine(string.Format("Id:{0}", (itemNode as XmlElement).GetAttribute("id")));
}
}
}
}
I have tried to setup a Dialogue tree within unity using XML (I have not used XML much before so am unsure if the way i am going is correct at all)
So I am trying to get the first text element from this dialogue tree but when i call the XML file and say where it is i am getting the everything stored in that branch.
Am i using the correct .XML to be able to do this also as i seen people say use .XML.LINQ or .XML.Serialization not just .XML is this correct for my case ??
Code:
using UnityEngine;
using System.Collections;
using System.IO;
using System.Xml;
using UnityEngine.UI;
using System.Collections.Generic;
public class DialogTree
{
public string text;
public List<string> dialogText;
public List<DialogTree> nodes;
public void parseXML(string xmlData)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new StringReader(xmlData));
XmlNode node = xmlDoc.SelectSingleNode("dialoguetree/dialoguebranch");
text = node.InnerXml;
XmlNodeList myNodeList = xmlDoc.SelectNodes("dialoguebranch/dialoguebranch");
foreach (XmlNode node1 in myNodeList)
{
if (node1.InnerXml.Length > 0)
{
DialogTree dialogtreenode = new DialogTree();
dialogtreenode.parseXML(node1.InnerXml);
nodes.Add(dialogtreenode);
}
}
}
}
And here is a picture of the XML.
So i am trying to grab the first element of text then late on there response it will go to branch 1 or 2
<?xml version='1.0'?>
<dialoguetree>
<dialoguebranch>
<text>Testing if the test prints</text>
<dialoguebranch>
<text>Branch 1</text>
<dialoguebranch>
<text>Branch 1a</text>
</dialoguebranch>
<dialoguebranch>
<text>Branch 1b</text>
</dialoguebranch>
</dialoguebranch>
<dialoguebranch>
<text>Branch 2</text>
</dialoguebranch>
</dialoguebranch>
</dialoguetree>
You're getting everything in that branch because XmlNode.InnerXML returns everything in that node. See the documentation for more information on that.
You should use the branch as the base for only looking at its children, instead of starting at xmlDoc every time. Also, you need an entry point to get inside of the first dialoguetree element and then ignore that. Finally, I would only create one XmlDocument and just pass around nodes in your recursion.
Altogether, this might look like this:
public class DialogTree
{
public string text;
public List<DialogTree> nodes = new List<DialogTree>();
public static DialogTree ParseXMLStart(string xmlData)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new Stringreader(xmlData));
XmlNode rootNode = xmlDoc.SelectSingleNode("dialoguetree/dialoguebranch");
DialogTree dialogTree = new DialogTree();
dialogTree.ParseXML(rootNode);
return dialogTree;
}
public void ParseXML(XmlNode parentNode)
{
XmlNode textNode = parentNode.SelectSingleNode("text");
text = textNode.InnerText;
XmlNodeList myNodeList = parentNode.SelectNodes("dialoguebranch");
foreach (XmlNode curNode in myNodeList)
{
if (curNode.InnerXml.Length > 0)
{
DialogTree dialogTree = new DialogTree();
dialogTree.ParseXML(curNode);
nodes.Add(dialogTree);
}
}
}
}
And you could use it like so:
string xmlStringFromFile;
DialogTree dialogue = DialogTree.ParseXMLStart(xmlStringFromFile);
All of this code is untested but I hope the general idea is clear. Let me know if you find any errors in the comments below and I will try to fix them.
Below is the XML sample. 'file' is the repeated node. Need to read 'filename' and 'sftp1' ,'sftp2','sftp3' elements values from 'sftp'. we need to repeat the same for each 'file' Node.
<FTPLocations>
<file>
<filedetails>
<filename>sample.txt</filename>
</filedetails>
<sftp>
<sftp1>
<sftp-username>UN</sftp-username>
<sftp-password>PW</sftp-password>
<sftp-host>ipaddress</sftp-host>
<sftp-path>path</sftp-path>
</sftp1>
<sftp2>
<sftp-username>UN</sftp-username>
<sftp-password>PW</sftp-password>
<sftp-host>ipaddress</sftp-host>
<sftp-path>path</sftp-path>
</sftp2>
<sftp3>
<sftp-username>UN</sftp-username>
<sftp-password>PW</sftp-password>
<sftp-host>ipaddress</sftp-host>
<sftp-path>path</sftp-path>
</sftp3>
</sftp>
</file>
<file>
<filedetails>
<filename>sample.txt</filename>
</filedetails>
<sftp>
<sftp1>
<sftp-username>UN</sftp-username>
<sftp-password>PW</sftp-password>
<sftp-host>ipaddress</sftp-host>
<sftp-path>path</sftp-path>
</sftp1>
<sftp2>
<sftp-username>UN</sftp-username>
<sftp-password>PW</sftp-password>
<sftp-host>ipaddress</sftp-host>
<sftp-path>path</sftp-path>
</sftp2>
<sftp3>
<sftp-username>UN</sftp-username>
<sftp-password>PW</sftp-password>
<sftp-host>ipaddress</sftp-host>
<sftp-path>path</sftp-path>
</sftp3>
</sftp>
</file>
</FTPLocations>
Please suggest me how I can achieve this using C#.
You can access elements of your XML using following code:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("YOUR_PATH_TO_XML");
//for sftp1
XmlNodeList sftp1_hd = xmlDoc.GetElementsByTagName("sftp1");
foreach (XmlNode sftp1_node in sftp1_hd)
{
foreach (XmlNode sftp1_child_nodes in sftp1_node.ChildNodes)
{
Console.WriteLine(sftp1_child_nodes.LocalName);
Console.WriteLine(sftp1_child_nodes.InnerText);
}
}
//for sftp2
XmlNodeList sftp2_hd = xmlDoc.GetElementsByTagName("sftp2");
foreach (XmlNode sftp2_node in sftp2_hd)
{
foreach (XmlNode sftp2_child_nodes in sftp2_node.ChildNodes)
{
Console.WriteLine(sftp2_child_nodes.LocalName);
Console.WriteLine(sftp2_child_nodes.InnerText);
}
}
Try xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication47
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("sftp").Elements().Select(x => new
{
name = x.Name.LocalName,
username = (string)x.Element("sftp-username"),
password = (string)x.Element("sftp-password"),
host = (string)x.Element("sftp-ipaddress"),
path = (string)x.Element("sftp-path")
}).ToList();
}
}
}
Thank you very much for reading my question.
the bottom is the sample of my xml file.please refer that.
i did some xml files before, but by "CMarkXml". "IntoElement, OutofElement", is very clear.
but when C#...i was lost..
1: how to read & write my xml file without using the tag name. i see some articles about operation on xml file by c#, but all assumed that known the tag name.
2: if without tag name, it is very difficult or not recommend. then how to read & write my xml file by XmlDocument? (sorry, but no Ling please, i am very faint with that...).
3: my idear is, for the xml file, get out some section, we still could parse the section by xmldocument.
4: for the write/modify the xml file, of course, should contain delete some section, delete some "leaf", change the attributes...
Thank you very much for reading the long question, and any help i will very appreciate. If you have a good sample code but not continent paste them here, could you send it to "erlvde#gmail.com"?
<root>
<a>i belong to a</a>
<b>
<bb>
<bb>1</bb>
<bb>2</bb>
<bb>3</bb>
<bb>4</bb>
<bb>5</bb>
</bb>
<bb>
<bb>1</bb>
<bb>2</bb>
<bb>3</bb>
<bb>4</bb>
<bb>5</bb>
<bb>
....(other <bb>)
</b>
</root>
Read your xml into XmlDocument:
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("XML HERE");
Access child nodes:
xmlDocument.ChildNodes[1]
But it's also true that it's very error prone
You can also check if you have child nodes at all:
xmlDocument.HasChildNodes
And get number of child nodes:
xmlDocument.ChildNodes.Count
It looks to me like your elements names contain identifiers. If that is the case, and you have control over the XML schema, I would highly recommend changing your XML to contain elements and/or attributes indicating your identifiers and then use the built in XmlSerializer class for serializing to and from XML. It has many modifiers available, such as XmlElement and XmlAttribute among many others, for formatting the output.
Here is a tutorial to get you started.
If possible, change your XML to something like following which would make it far simpler to manipulate...again if changing the schema is a possibility.
<root>
<a>i belong to a</a>
<b>
<bb id="1">
<bb>1</bb>
<bb>2</bb>
<bb>3</bb>
<bb>4</bb>
<bb>5</bb>
</bb>
<bb id="2">
<bb>1</bb>
<bb>2</bb>
<bb>3</bb>
<bb>4</bb>
<bb>5</bb>
<bb>
</b>
</root>
Edit this edit reflects the changes you made to your XML
Here is a simple console application which will serialize an object to an XML file and then rehydrate it.
Expected XML
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<a>i belong to a</a>
<b>
<bb>
<bb>1</bb>
<bb>2</bb>
<bb>3</bb>
<bb>4</bb>
<bb>5</bb>
</bb>
<bb>
<bb>1</bb>
<bb>2</bb>
<bb>3</bb>
<bb>4</bb>
<bb>5</bb>
</bb>
</b>
</root>
Simple Console Application Demonstration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var items = new root
{
a = "i belong to a",
b = new List<bb>
{
new bb
{
bbClassProperty = new List<int>
{
1,
2,
3,
4,
5
}
},
new bb
{
bbClassProperty= new List<int>
{
1,
2,
3,
4,
5
}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(root));
using (var textWriter = new StreamWriter(#"C:\root.xml"))
{
serializer.Serialize(textWriter, items);
textWriter.Close();
}
using (var stream = new StreamReader(#"C:\root.xml"))
{
var yourObject = serializer.Deserialize(stream);
}
Console.Read();
}
}
#region [Classes]
public class root
{
public string a { get; set; }
public List<bb> b { get; set; }
}
public class bb
{
[XmlElement("bb")]
public List<int> bbClassProperty { get; set; }
}
#endregion
}
Look into the ChildNodes (and similar) properties and methods on your XmlElement object. These will let you iterate over the children of a node and you can then ask that node for its name.
If you have a XmlNode object, you can use XMLNode.FirstChild to get the child, if it has any. You can also use XMLNode.NextSibling to get the next Node of the same parent node.
Why can't you use the names of the nodes? It's the easiest and most common way. Especially if you use XPath or similar.
XPath is also the answer to your second question.
U can use the class XML reader, a simple example is given here.
using System;
using System.Xml;
class Program
{
static void Main()
{
// Create an XML reader for this file.
using (XmlReader reader = XmlReader.Create("perls.xml"))
{
while (reader.Read())
{
// Only detect start elements.
if (reader.IsStartElement())
{
// Get element name and switch on it.
switch (reader.Name)
{
case "perls":
// Detect this element.
Console.WriteLine("Start <perls> element.");
break;
case "article":
// Detect this article element.
Console.WriteLine("Start <article> element.");
// Search for the attribute name on this current node.
string attribute = reader["name"];
if (attribute != null)
{
Console.WriteLine(" Has attribute name: " + attribute);
}
// Next read will contain text.
if (reader.Read())
{
Console.WriteLine(" Text node: " + reader.Value.Trim());
}
break;
}
}
}
}
}
}
The input file text is:
<?xml version="1.0" encoding="utf-8" ?>
<perls>
<article name="backgroundworker">
Example text.
</article>
<article name="threadpool">
More text.
</article>
<article></article>
<article>Final text.</article>
</perls>
Output
Start element.
Start element.
Has attribute name: backgroundworker
Text node: Example text.
Start element.
Has attribute name: threadpool
Text node: More text.
Start element.
Text node:
Start element.
Text node: Final text.enter code here
You can use the following code to if the file does not contain the headers, in the example above.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
reader = XmlReader.Create(filePath, settings)
Would something like this help?
void Iterate(XmlNode parent) {
//do something with
//parent.Name
//parent.Value
//parent.Attributes
foreach(XmlNode child in parent.ChildNodes) {
Iterate(child);
}
}
XmlDocument document = new XmlDocument();
document.Load(filename);
XmlNode parent = document.DocumentElement;
Iterate(parent);
You could also store it like that (sorry for any syntactical error, didn't run it)
public class Document {
public Element DocumentElement { set; get; }
private void Load(string fileName) {
XmlDocument document = new XmlDocument();
document.Load(fileName);
DocumentElement = new Element(this, null);
DocumentElement.Load(document.DocumentElement);
}
}
public class Element {
public string Name { set; get; }
public string Value { set; get; }
//other attributes
private Document document = null;
private Element parent = null;
public Element Parent { get { return parent; } }
public List<Element> Children { set; get; }
private int order = 0;
public Element(Document document, Element parent) {
Name = "";
Value = "";
Children = new List<LayoutElement>();
this.document = document;
this.parent = parent;
order = parent != null ? parent.Children.Count + 1 : 1;
}
private Element GetSibling(bool left) {
if(parent == null) return null;
int add = left ? -1 : +1;
Element sibling = parent.Children.Find(child => child.order == order + add);
return sibling;
}
public Element GetLeftSibling() {
return GetSibling(true);
}
public Element GetRightSibling() {
return GetSibling(false);
}
public void Load(XmlNode node) {
Name = node.Name;
Value = node.Value;
//other attributes
foreach(XmlNode nodeChild in node.Children) {
Element child = new Element(document, this);
child.Load(nodeChild);
Children.Add(child);
}
}
}
Document document = new Document();
document.Load(fileName);
For changing/deleting right now you could iterate the tree and find elements by name, but since name is not unique, you would affect many elements at once. You could add an unique id in every tag like
<bb id="bb1"/>
Then read it in Load function like
id = ((XmlElement)node).GetAttribute("id");
and use this id to iterate through the tree. Sorry I don't have time right now to provide something more detailed.
I have a Java generated (List Collection) XML format of:
<java.util.Collections>
<org.yccheok.jstock.engine.Stock>
<code>
<code> RBS.L</code>
</code>
<symbol>
<symbol> ROYAL BK SCOTL GR</symbol>
</symbol>
<name> ROYAL BK SCOTL GR</name>
<board> London</board>
<industry> Unknown</industry>
<prevPrice> 23.74</prevPrice>
<openPrice> 23.41</openPrice>
<lastPrice> 24.4</lastPrice>
<highPrice> 24.855</highPrice>
<lowPrice> 23.0</lowPrice>
<volume> 51353968</volume>
<changePrice> 0.66</changePrice>
<changePricePercentage> 2.78</changePricePercentage>
<lastVolume> 795</lastVolume>
<buyPrice> 24.39</buyPrice>
<buyQuantity> 51203</buyQuantity>
<sellPrice> 24.4</sellPrice>
<sellQuantity> 370763</sellQuantity>
<secondBuyPrice> 0.0</secondBuyPrice>
<secondBuyQuantity> 0</secondBuyQuantity>
<secondSellPrice> 0.0</secondSellPrice>
<secondSellQuantity> 0</secondSellQuantity>
<thirdBuyPrice> 0.0</thirdBuyPrice>
<thirdBuyQuantity> 0</thirdBuyQuantity>
<thirdSellPrice> 0.0</thirdSellPrice>
<thirdSellQuantity> 0</thirdSellQuantity>
<calendar>
<time> 1319038099446</time>
<timezone> America/New_York</timezone>
</calendar>
</org.yccheok.jstock.engine.Stock>
</java.util.Collections>
I am trying to extract the tag values of the code inner tag and changePricePercentage in C#. I am also trying to pre-populate a DataTable with these values. How do I handle the inner tag of code as well? Even though I am no expert, here is my C# source code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data;
namespace XMLParser
{
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable();
table.Columns.Add("code", typeof(string)); ;
table.Columns.Add("changePricePercentage", typeof(double));
// Create a new XmlDocument
XmlDocument doc = new XmlDocument();
// Load data
doc.Load(#"C:\...\realtimestock.xml");
// Set up namespace manager for XPath
// Get forecast with XPath
//XmlNodeList nodes = doc.SelectNodes("org.yccheok.jstock.engine.Stock", ns);
XmlNodeList nodes = doc.SelectNodes("org.yccheok.jstock.engine.Stock");
// You can also get elements based on their tag name and namespace,
// though this isn't recommended
//XmlNodeList nodes = doc.GetElementsByTagName("org.yccheok.jstock.engine.Stock");
// "http://xml.weather.yahoo.com/ns/rss/1.0");
foreach (XmlNode node in nodes)
{
// Console.WriteLine("{0}: {1}, {2}F - {3}F",
// node.Attributes["code"].InnerText,
// node.Attributes["changePricePercentage"].InnerText);
Console.WriteLine("1: {0} 2: {1}", node.Attributes["code"].InnerText,
node.Attributes["changePricePercentage"].InnerText);
table.Rows.Add(node.Attributes["code"].InnerText, node.Attributes["changePricePercentage"].InnerText);
Console.ReadKey();
}
}
}
}
How would I get my code to accomplish this task?
P.S. This Stackoverflow editor would not accept my XML code properly so I had to edit with the actual symbol names. Sorry
Thanks
Try this:
XmlNodeList nodes = doc.SelectNodes("//org.yccheok.jstock.engine.Stock");
foreach (XmlElement element in nodes)
{
Console.WriteLine("1: {0} 2: {1}",
element.SelectSingleNode("code").InnerText,
element.SelectSingleNode("changePricePercentage").InnerText);
}
Console.ReadKey();
Your code and changePricePercentage nodes are elements, not attributes, that was your mistake.