Load Specific XML Node Values C# - c#

I am trying to get the attribute values of all nodes with the tag name "Event" into a comboBox on a WindowsForm. I have tried this code below, however, nothing populates in the comboBox.
if (selectEventComboBox.SelectedIndex != -1)
{
string filePath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ "\\" + selectFileComboBox.SelectedItem.ToString()
+ "dogs.xml";
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList eventList = doc.GetElementsByTagName("Event");
for (int count = 0; count < eventList.Count; count++)
{
selectEventComboBox.Items.Add(eventList[count].Attributes.ToString());
}
}

This works fine
XmlDocument doc = new XmlDocument();
doc.Load("myxml.xml");
XmlNode root = doc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("//Event");
for (int i = 0; i < nodeList.Count; i++)
{
Console.WriteLine("row: {0}, InnerText: {1}, ID: {2}",i, nodeList[i].InnerText, nodeList[i].Attributes["id"].Value);
}
Contents of myxml.xml
<?xml version="1.0" encoding="utf-8" ?>
<root>
<Event id="1">Event one</Event>
<Event id="2">Event two</Event>
<Event id="3">Event three</Event>
<Event id="4">Event four</Event>
</root>

Related

Create XML string using C# XmlElement

I am trying to create an XML string but the expected output is different from this code
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("Employee");
xml.AppendChild(root);
for (int i = 1; i < datacount; i++)
{
XmlElement child = xml.CreateElement("EmployeeName");
child.SetAttribute("value", "Name1");
root.AppendChild(child);
}
string xmlString = xml.OuterXml;
Expected output:
<?xml version="1.0" encoding="utf-8" ?>
<Employee>
<EmployeeName>Name1</EmployeeName>
<EmployeeName>Name2</EmployeeName>
</Employee>
Current output:
<?xml version="1.0" encoding="utf-8" ?>
<Employee>
<EmployeeName Value = "Name1" />
<EmployeeName Value = "Name1" />
</Employee>
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("Employee");
xml.AppendChild(root);
//Create a new node and add it to the document.
//The text node is the content of the price element.
for (int i = 1; i < datacount; i++)
{
XmlElement elem = xml.CreateElement("EmployeeName");
XmlText text = xml.CreateTextNode("Name");
xml.DocumentElement.AppendChild(elem);
xml.DocumentElement.LastChild.AppendChild(text);
}
string xmlString = xml.OuterXml;
or you can use
child.InnerText="Name1";

C# XML getting a duplicated empty node?

I am creating a xml document using the following C# code:
XmlDocument finalDoc = new XmlDocument();
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = finalDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = finalDoc.DocumentElement;
finalDoc.InsertBefore(xmlDeclaration, root);
//(2) string.Empty makes cleaner code
XmlElement element1 = finalDoc.CreateElement(string.Empty, "root", string.Empty);
finalDoc.AppendChild(element1);
for (int i = 0; i < 5; i++)
{
XmlElement element2 = finalDoc.CreateElement(string.Empty,"song", string.Empty);
element2.SetAttribute("title", "title" + i);
element1.AppendChild(element2);
for (int k=0; k<5;k++)
{
XmlElement element3 = finalDoc.CreateElement(string.Empty, "line", string.Empty);
element3.InnerText = "text " + k;
element2.AppendChild(element3);
}
element1.AppendChild(element2);
}
finalDoc.Save("C:\\Users\\adm\\Downloads\\finalDoc.xml");
and I am getting the following output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<song title="title 0" />
<song title="title 0">
<line>text 0</line>
<line>text 1</line>
<line>text 2</line>
<line>text 3</line>
<line>text 4</line>
</song>
<song title="title 1" />
<song title="title 1">
...
</song>
...
</root>
As you can see, I am having a duplicated empty "song" node for some reason, what am I missing here?
I don't see anything out of order here, could someone please help, thanks in advance.
You AppendChild 2 times element2. Remove first one
for (int i = 0; i < 5; i++)
{
XmlElement element2 = finalDoc.CreateElement(string.Empty,"song", string.Empty);
element2.SetAttribute("title", "title" + i);
for (int k=0; k<5;k++)
{
XmlElement element3 = finalDoc.CreateElement(string.Empty, "line", string.Empty);
element3.InnerText = "text " + k;
element2.AppendChild(element3);
}
element1.AppendChild(element2);
}
The line element1.AppendChild(element2); occurs twice in your for loop, third and last line in the loop.

How to convert XmlNodeList to Xmlstring to bind xml data with dataset

XmlDocument objXmldoc = new XmlDocument();
objXmldoc.Load(txtBrowseFilePath.Text);
XmlNodeList objxmlNodeList=null;
objxmlNodeList = objXmldoc.SelectNodes(#"/AppXmlLogWritter/LogData[LogDateTime/text()[starts-with(. , '" + dateTimePickerFromDate.Value.ToString("yyyyMMdd") + "')]]");
DataSet ds = new DataSet();
ds.ReadXml(objxmlNodeList);
How to convert XmlNodeList to Xmlstring to bind xml data with dataset
xml file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<AppXmlLogWritter>
<LogData>
<LogID>5678201301161640382918</LogID>
<LogDateTime>20130116164037</LogDateTime>
<LogType>Message</LogType>
<LogFlag>RISLogFlag</LogFlag>
<LogApplication>BaburaoLogApplication</LogApplication>
<LogModule>RISLogModule</LogModule>
<LogLocation>RISLogLocation</LogLocation>
<LogText>BaburaoLogText</LogText>
</LogData>
<LogData>
<LogID>5678201301161640382919</LogID>
<LogDateTime>20130116164038</LogDateTime>
<LogType>Warning</LogType>
<LogFlag>MACLogFlag</LogFlag>
<LogApplication>MACLogApplication</LogApplication>
<LogModule>MACLogModule</LogModule>
<LogLocation>MACLogLocation</LogLocation>
<LogText>MACLogText</LogText>
</LogData>
</AppXmlLogWritter>
try such a function:
private string XmlNodeListToString(XmlNodeList nodeList)
{
String returnStr = "";
if (nodeList != null)
{
foreach (XmlNode node in nodeList)
{
returnStr += node.OuterXml;
}
}
/*
//I think this is not needed from Dataset.ReadXml
returnStr = returnStr .Replace("&", "&");
returnStr = returnStr.Replace("<", "<");
returnStr = returnStr.Replace(">", ">");
returnStr = returnStr.Replace("'", "&apos;");
returnStr = returnStr.Replace("\"", """);
*/
return "<Root>"+returnStr+"</Root>";
}
Also from your comments seems that you have a long file name issue.
try objXmldoc.Load(#txtBrowseFilePath.Text);
or if it does not succeed
try something else like preceding filepath with \\?\ as i found out in this link
For example, "\\?\D:\very long path".

catch particular element from XML file

xml:
<?xml version="1.0" encoding="utf-8" ?>
<StudentList>
<student>
<name>Ram</name>
<Id>1</Id>
</student>
<student>
<name>Hari</name>
<Id>2</Id>
</student>
<student>
<name>Gita</name>
<Id>3</Id>
</student>
<student>
<name>Sita</name>
<Id>4</Id>
</student>
</StudentList>
In page load:
XmlDocument XD = new XmlDocument();
XD.Load(System.Web.HttpContext.Current.Server.MapPath("XmlFile.xml"));
XmlNodeList nodeListName = XD.GetElementsByTagName("student");
foreach (XmlNode xNode in nodeListName)
{
foreach (XmlElement xelement in xNode)
{
PlaceHolder pshd = new PlaceHolder();
LblDisplay.Text += xelement.FirstChild.Value + " ";
string Name += xelement.FirstChild.Value;
}
LblDisplay.Text += "<br/>";
}
i want to catch only name from the above xml file but i get name and id both.How can i do it plz help.
XmlDocument xml = new XmlDocument();
xml.LoadXml(System.Web.HttpContext.Current.Server.MapPath("XmlFile.xml"));
XmlNodeList xnList = xml.SelectNodes("/StudentList/student");
foreach (XmlNode xn in xnList)
{
string name= xn["name"].InnerText;
string Id= xn["Id"].InnerText;
}
Instead of iterating over xNode you just want its FirstChild:
foreach (XmlNode xNode in nodeListName)
{
string name = xNode.FirstChild.InnerText;
LblDisplay.Text += name + "<br/>";
}
You can also use LINQ to XML (in the System.Xml.Linq namespace), using XDocument:
XDocument xDoc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("XmlFile.xml"));
var names = from x in xDoc.Descendants("student")
select x.Element("name");
foreach (XElement studentName in names)
{
LblDisplay.Text += studentName.Value + " ";
}
LblDisplay.Text += "<br />";
If you want the id instead, you can substitute "Id" in the select x.Element("name"); line.
Alternatively, you could grab both name and Id and return them as a collection of anonymous types:
var students = from x in xDoc.Descendants("student")
select new
{
name = x.Element("name").Value,
id = x.Element("Id").Value
};
Which you could then access thusly:
foreach (var student in students)
{
LblDisplay.Text += student.name + " student.Id + " ";
}
Or whatever you wanted to do with it.
You can use XPath all the way:
nodeList = XD.SelectNodes("//student/name")
foreach (XMlNode node in nodeList){
LblDisplay.Text += node.Value + "<br/>";
}
String fileName = #"C:\Documents and Settings\aritra.ghosh\Desktop\Student.xml";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(fileName);
XmlNodeList list = xDoc.SelectNodes("StudentList/student/name");
foreach (XmlNode item in list)
{
Console.WriteLine(item.InnerText);
}

How to get an XML value out of another XML value at C#

I need to get a value out of an XML file...
I have this XML file for example:
<?xml version="1.0"?>
<hwids>
<user>
<userName>Ivar</userName>
<hwid>BFEB-FBFF-0000-06FD-C87C-FA30</hwid>
</user>
<user>
<userName>Jerremy</userName>
<hwid>BFE9-FBFF-0000-06E8-E41E-5034</hwid>
</user>
</hwids>
Now, if I have the value BFEB-FBFF-0000-06FD-C87C-FA30, how do I get the name Ivar, out of the xml file trough C#?
I used in my application something like this:
using System.Data;
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFullPath, XmlReadMode.Auto);
DataRow[] dataRows = dataSet.Tables["user"].Select("hwid like 'BFEB-FBFF-0000-06FD-C87C-FA30'");
if (dataRows.Length == 0)
return;
string sUser = dataRows[0]["userName"].ToString();
you can accomplish this also with XmlDocument of the System.Xml namespace, which is supported in .NET 3.0
var xml = "<?xml version=\"1.0\"?>" +
"<hwids> " + "<user>" +
"<userName>Ivar</userName>" +
"<hwid>BFEB-FBFF-0000-06FD-C87C-FA30</hwid>"+
"</user> " +
"<user>" +
"<userName>Jerremy</userName>" +
"<hwid>BFE9-FBFF-0000-06E8-E41E-5034</hwid>" +
"</user>" +
"</hwids>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var ret = doc.GetElementsByTagName("userName");
for (int i = 0; i < ret.Count; i++)
{
Debug.WriteLine(ret.Item(i).InnerText);
}
I think this should work:
XElement root = XElement.Load("file.xml");
IEnumerable<XElement> hws =
from el in root.Elements("user")
where (string)el.Element("userName") == "Ivar"
select el.Descendant("hwid);
Haven't tested it out.

Categories

Resources