XML select single node not returning anything - c#

I have the following method that is supposed to return a string that holds the calories for a given food item in an xml menu.
public string calorieCount(int choice)
{
string calCount = "250";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.DocumentElement;
XmlNode node = doc.SelectSingleNode("/menu/item[#name='Burger']/calories");
string checker = node.Value;
MessageBox.Show(checker);//returning nothing
return checker;
}
And my XML file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<menu>
<!-- Burger -->
<item name="Burger">
<name>Burger</name>
<price>$5.99</price>
<calories>500</calories>
<description>A burger made with 100% angus beef and grilled to your liking. Served with fries</description>
<count>25</count>
</item>
Why is it returning an empty string? Is my call to SelectSingleNode incorrect?
Thank you in advance.

Use InnerText instead of Value
Replace
string checker = node.Value;
With
string checker = node.InnerText;

Related

Reading XML file results in index out of range exception

Using C# I have an XML file like
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account>
<name>Jani</name>
</Account>
</root>
and I also have a function to read the name node as:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("lib//user.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
label1.Text = name.ToString();
but I am getting index out of range error as:
Why is this happening?
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
node is your root node. Which looks like this:
<root>
How many attributes does it have? None, as it turns out. An attribute in XML is one of these bar="baz" things:
<foo bar="baz">
node.Attributes[0] refers to the first attribute. There is no first attribute, there's no second attribute -- you didn't use attributes in this XML at all. Hence, that's out of range. There's no first item in an empty collection.
What you want is an element named name, which is farther down inside your XML tree.
Probably this:
var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");
And then you'll want to look at node.InnerText to get "Jani" out of it.
You are trying to read node.Attributes[0].Value but there is no attribtues in your sample XML file. Not sure of the exact syntax but it should probably be closer to node.Value
As mentioned by other answers, your current XML does not have attributes.
private void DoIt()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
//string name = node.Attributes[0].Value;
string name = node["Account"].InnerText;
}
If your XML did have attributes
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account name="Jani" />
</root>
Then you could do this:
private void DoItAgain()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data2.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node["Account"].Attributes[0].Value;
}

Xml delete node by elements value

Here is xml file:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
<PageInfo>
<ID>0</ID>
<NUM>5</NUM>
<URL>er.php</URL>
</PageInfo>
<PageInfo>
<ID>1</ID>
<NUM> 12345</NUM>
<URL>/out/out.ViewFolder.php</URL>
</PageInfo>
</Data>
I have tried alot of ways (for a week now) to delete certain node (PageInfo) by element (ID,NUM,URL) in this xml file.
There are few approaches I have tried:
1st approach:
XmlDocument docc = new XmlDocument();
docc.LoadXml(AppDomain.CurrentDomain.BaseDirectory + "/WebData.xml");
XmlNode nodee = docc.SelectSingleNode("/Data/PageInfo/ID[2]");
nodee.RemoveAll();
2nd approach:
XmlDocument document = new XmlDocument();
document.Load(AppDomain.CurrentDomain.BaseDirectory + "/WebData.xml");
XmlNodeList nodes = document.DocumentElement.SelectNodes("/Data/PageInfo");
string ID, NUM, URL;
foreach (XmlNode node in nodes)
{
ID = node.SelectSingleNode("ID").InnerText;
NUM = node.SelectSingleNode("NUM").InnerText;
URL = node.SelectSingleNode("URL").InnerText;
node.RemoveAll();
Console.WriteLine(ID + " " + NUM + " " + URL + "\n");
}
1st solution does not trigger and exception but nothing happens, 2nd solution throws an exception: Data at the root level is invalid.
How one would be able to delete nodes by elements value in an xml file? (LINQ is fine)
Disclaimer: all solutions I have found on StackOverflow does not work for my certain case.
Based on the ID, please try this solution :
First approach
string xml = AppDomain.CurrentDomain.BaseDirectory + "/WebData.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xml);
XmlNode t = xmlDoc.SelectSingleNode("/Data/PageInfo[ID='0']");
t.ParentNode.RemoveChild(t);
xmlDoc.Save(xml);
Second approach : Linq
XDocument xmlDoc = XDocument.Load(xml);
var pageInfo = (from xml2 in xmlDoc.Descendants("PageInfo")
where xml2.Element("ID").Value == "0"
|| xml2.Element("NUM").Value == "5"
|| xml2.Element("URL").Value == "er.php"
select xml2).FirstOrDefault();
pageInfo.Remove();
xmlDoc.Save(xml);
// output
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
<PageInfo>
<ID>1</ID>
<NUM> 12345</NUM>
<URL>/out/out.ViewFolder.php</URL>
</PageInfo>
</Data>
As <Data> is an array so you can deserialize it in a classData which has List<PageInfo> so you can update your data accordingly and then serialize it back in your file.
Example:
XmlArray("Data")]
public class Data
{
[XmlArrayItem("PageInfo")]
public List<PageInfo> pageInfos = new List<PageInfo>();
}
public class PageInfo
{
public int ID;
public int NUM;
public string URL;
}
Now you can apply queries on your list and then deserialize your Data class back to file. See This Link for Serializing guide.

How to get the values of all the elements in an XML into an array?

For example :
I have the following XML,
<?xml version="1.0" encoding="utf-8"?>
<TEST>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</Test>
I would like to get the values from the tags "SyncByte", "SOM", "PADD" and "LENLSB" into a single array. Is there an option within XML to accomplish this?
P.S. There are close to 20+ tags in the XML and not all tags contain values all the time. Hence if there is a single command to get all the values of the XML, then it would be great.
With Linq to Xml:
var xml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<Test>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</Test>";
var doc = XDocument.Parse(xml);
string[] values = doc.Root.Descendants().Select(x => x.Value).ToArray();
First:
your xml formate is wrong , it should be:
<?xml version="1.0" encoding="utf-8"?>
<TEST>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</TEST> <!--END Tag should same as TEST -->
Then you can query them like this:
var xml=XDocument.Load("d:\\test.xml");
var list=xml.Descendants("TEST")
.Select(x=>new
{
SyncByte=x.Element("SyncByte")==null?"":x.Element("SyncByte").Value,
SOM=x.Element("SOM")==null?"":x.Element("SOM").Value,
LENLSB=x.Element("LENLSB")==null?"":x.Element("LENLSB").Value
});
You can get the child of any parent node through 'XmlElement.ChildNodes' and store it in collection.
for eg :
static int Main(string[] args)
{
string strFilename = "Input.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
XmlElement elm = xmlDoc.DocumentElement;
XmlNodeList lstVideos = elm.ChildNodes;
for (int i = 0; i < lstVideos.Count; i++)
Console.WriteLine("{0}",lstVideos[i].InnerText );
}
else
Console.WriteLine("The file {0} could not be located",
strFilename);
Console.WriteLine();
return 0;
}

C# how to create a custom xml document

I'm really just trying to create a custom xml document for simple configuration processing.
XmlDocument xDoc = new XmlDocument();
string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie"};
foreach (string node in NodeArray)
{
XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element,node.Split('|')[0],null);
//xmlNode.Value = node.Split('|')[0];
xmlNode.InnerText = node.Split('|')[1];
xDoc.DocumentElement.AppendChild(xmlNode);
}
What i'm trying to get is this.
<?xml version="1.0" encoding="ISO-8859-1"?>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>
i get not set to value of an object at xDoc.DocumentElement.AppendChild(xmlNode);
Unfortunately, You can't make that XML structure.
All XML documents must have a single root node. You can't have more.
Try something like this
XmlDocument xDoc = new XmlDocument();
xDoc.AppendChild( xDoc.CreateElement("root"));
string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie" };
foreach (string node in NodeArray)
{
XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element, node.Split('|')[0], null);
//xmlNode.Value = node.Split('|')[0];
xmlNode.InnerText = node.Split('|')[1];
xDoc.DocumentElement.AppendChild(xmlNode);
}
It is not possible to have that XML structure as XML MUST have a single root element. You may want to try:
<?xml version="1.0" encoding="ISO-8859-1"?>
<items>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>
</items>

Problem in reading XML node with unknown root/parent nodes

I have been trying to read an xml file. I have to extract value of nodes "Date" and "Name", but the problem is, they might appear at any level in XML hierarchy.
So when I try with this code,
XmlDocument doc = new XmlDocument();
doc.Load("test1.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//*");
string date;
string name;
foreach (XmlNode node in nodes)
{
date = node["date"].InnerText;
name = node["name"].InnerText;
}
and the XML file is ::
<?xml version="1.0" encoding="utf-8"?>
<root>
<child>
<name>Aravind</name>
<date>12/03/2000</date>
</child>
</root>
the above code errors out, as <name> and <date> are not immediate child Elements of root.
is it possible to assume that parent/root nodes are unknown and just with the name of the nodes, copy the values ??
Depending on the exception you are getting, this may or may not be the exact solution. However, I would definitely check that date and name exist before doing a .InnerText on them.
foreach (XmlNode node in nodes)
{
dateNode = node["date"];
if(dateNode != null)
date = dateNode.InnerText;
// etc.
}
I would read up on XPATH and XPATH for C# to do this more efficiently
http://support.microsoft.com/kb/308333
http://www.w3schools.com/XPath/xpath_syntax.asp
Here's a little method that should allow you to get the innerText easily.
function string GetElementText(string xml, string node)
{
XPathDocument doc = new XPathDocument(xml);
XPathNavigator nav = doc.CreateNavigator();
XPathExpression expr = nav.Compile("//" + node);
XPathNodeIterator iterator = nav.Select(expr);
while (iterator.MoveNext())
{
// return 1st but there could be more
return iterator.Current.Value;
}
}
Try to use LINQ:
string xml = #"<?xml version='1.0' encoding='utf-8'?>
<root>
<date>12/03/2001</date>
<child>
<name>Aravind</name>
<date>12/03/2000</date>
</child>
<name>AS-CII</name>
</root>";
XDocument doc = XDocument.Parse(xml);
foreach (var date in doc.Descendants("date"))
{
Console.WriteLine(date.Value);
}
foreach (var date in doc.Descendants("name"))
{
Console.WriteLine(date.Value);
}
Console.ReadLine();
The Descendants method allows you to get all the elements that have a specified name.

Categories