Value of xml node returning as null - c#

I have an xml document that I am loading in my asp .net application. It is structured like this
-<Event>
<Event_Name>Special Name</Event_Name>
<Event_Date>5/27/2016 12:00:00 AM</Event_Date>
<Event_Description>Event Description</Event_Description>
</Event>
I am loading it in my code behind like this
XmlDocument doc = new XmlDocument();
string path = Server.MapPath("~/NewsXMLNews.xml");
doc.Load(path);
This loads properly. The problem is, I want to set the Event_Name as the text of a label on my aspx page. I do this using the following code
string nameOfEvent = doc.SelectSingleNode("Event_Name").ToString();
eventName.Text = nameOfEvent;
The problem is that nameOfEvent is coming back as null, so I get a nullReferenceException
I'm not exactly what I'm doing incorrectly here.

Since you already checked the path is correct and the document is properly loaded I think you just need to change the following line:
string nameOfEvent = doc.SelectSingleNode("/Event/Event_Name").InnerText;
Edit: I check with following steps that xml loading process works:
I remove the minus before in described xml file and saved
following lines as c:\temp\Event.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Event>
<Event_Name>Special Name</Event_Name>
<Event_Date>5/27/2016 12:00:00 AM</Event_Date>
<Event_Description>Event Description</Event_Description>
</Event>
Then I succeeded in running:
public Form1()
{
InitializeComponent();
XmlDocument doc = new XmlDocument();
string path = "c:\\temp\\Event.xml";
doc.Load(path);
string nameOfEvent = doc.SelectSingleNode("/Event/Event_Name").InnerText;
eventName.Text = nameOfEvent;
}
In my window I see Label named eventName text is Special Name
as expected.

This should work:
XmlNode nameOfEvent = doc.SelectSingleNode("/Event/Event_Name");
string text = nameOfEvent.InnerText;
eventName.Text = text;

Related

Parsing XML Using C# in uwp Xaml

How do you get the data from description in the tag something: <something description = "something else"> </something> using c# in uwp.
Here is the test code to show how to get the XML node attribute value:
private void GetContent()
{
string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><body><content title =\"XML File!\"></content></body>";
var doc = new XmlDocument();
doc.LoadXml(xml);
var tags=doc.GetElementsByTagName("content");
if (tags.Count > 0)
{
var firstContent = tags.First();
string result = firstContent.Attributes.GetNamedItem("title").InnerText;
}
}
Tips
In UWP, loading an XmlDocument via a path is not recommended. It is best to get the XML file first, read all the text, and load the XmlDocument via text.
The XmlDocument prefix namespace is Windows.Data.Xml.Dom, NOT System.Xml
Best regards.

How to change update the element value in XML with C#?

I have a xml file and wanted to update and save the value of target load with C# code. My code is as below which is trying to xml shown below -
var fileName = textBox1.Text;
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(fileName);
xmlDoc.SelectSingleNode("factoryTest/targetLoad").InnerText = "80";
xmlDoc.Save(fileName);
<?xml version="1.0" encoding="utf-8"?>
<factoryTest xmlns="urn:gcpm">
<targetLoad>90</targetLoad>
<isAccepted>true</isAccepted>
<isCertified>true</isCertified>
<isAtRatingConditions>true</isAtRatingConditions>
<supervisorName>Eric Larson</supervisorName>
</factoryTest>
I have resolved this issue.
XDocument xdoc = XDocument.Load(tFileName);
xdoc.Elements("{urn:gcpm}factoryTest").Elements("{urn:gcpm}targetLoad").FirstOrDefault().Value = textBox2.Text;
xdoc.Save(tFileName);

Load XML in C# InnerText

I have a C# service where I loop every 1 seconds trough a directory looking for XML files.
These XML files may look like this:
<?xml version="1.0" encoding="UTF-8"?>
<job>
<type>freelance</type>
<text>blah</text>
</job>
In a foreach I do the following:
var doc = new XmlDocument();
doc.LoadXml(xmlFile);
XmlNode xmltype = doc.DocumentElement.SelectSingleNode("/job/type");
And than I would like to use these strings to use in my program, however. Using xmltype.InnerText does not work. Documentation on MSDN does not provide me with anything new and I would like to know what I am doing wrong.
First you have to check the xml file.whether is there any data or not.
after that take the one particular node check for innerText.
for example
This is the Text
XmlNode xmlType = doc.DocumentElement.SelectSingleNode("/job/type");
xmlType.innerText = "This is the Text";
xmlType.Value = "Stack";
This following console program will output "freelance". I think the issue may be with some of your XML - do all of your XML docs follow the same schema? I am guessing that the code fails with a NullReferenceException at some point. I've added a null check to protect against this possible scenario.
To help debug your service I tend to use the technique described here to run the app as console application (for easy debugging) or windows service.
using System;
using System.Xml;
public class Program
{
static string xmlFile = #"<?xml version=""1.0"" encoding=""UTF-8""?>
<job>
<type>freelance</type>
<text>blah</text>
</job>";
public static void Main()
{
var doc = new XmlDocument();
doc.LoadXml(xmlFile);
XmlNode xmltype = doc.DocumentElement.SelectSingleNode("/job/type");
if(xmltype==null)
{
Console.WriteLine("/job/type not found");
} else {
Console.WriteLine(xmltype.InnerText);
}
}
}
Try this:
string str = xmltype.Value;

How to read an XML document in C# with a namespace that has no associated prefix

I am trying to read OSIS formatted documents. I have cut the document down to a simple fragment:
<?xml version="1.0" encoding="utf-8"?>
<osis xmlns="http://www.bibletechnologies.net/2003/OSIS/namespace">
<osisText osisRefWork="Bible" osisIDWork="kjv" xml:lang="en">
</osisText>
</osis>
I try to read it with this sample code from the MSDN documentation:
XPathDocument document = new XPathDocument("osis.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("/osis/osisText");
while (nodes.MoveNext())
{
Console.WriteLine(nodes.Current.Name);
}
The problem is that the selection contains no nodes and throws no exception. Since the code discards the root tag, I can't read the document. If I remove the xmlns="http://www.bibletechnologies.net/2003/OSIS/namespace" from the root osis tag, it works just fine. The offensive URL returns a 404 code, but otherwise I see nothing wrong with this XML. Can someone explain why this code won't read the document? What options do I have besides hand editing every document before trying to load it?
Your XPath expression is missing a namespace prefix.
The element that you're trying to select has a namespace URI of http://www.bibletechnologies.net/2003/OSIS/namespace, and XPath will not match these nodes using paths with an empty namespace URI.
I tested this revision in .NET 2.0 and it found the node as expected.
XPathDocument document = new XPathDocument("osis.xml");
XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager xmlns = new XmlNamespaceManager(navigator.NameTable);
xmlns.AddNamespace("osis", "http://www.bibletechnologies.net/2003/OSIS/namespace");
XPathNodeIterator nodes = navigator.Select("/osis:osis/osis:osisText", xmlns);
You can read the file to a string, replace the namespace in memory, and then load it using a string stream:
string s;
using(var reader = File.OpenText("osis.xml"))
{
s = reader.ReadToEnd();
}
s = s.Replace("xmlns=\"http://www.bibletechnologies.net/2003/OSIS/namespace\"", "");
Stream stream = new MemoryStream(Encoding.ASCII.GetBytes(s));
XPathDocument document = new XPathDocument("stream");
// Rest of the code

Trying to parse xml, but xmldocument.loadxml() is trying to download?

I have a string input that i do not know whether or not is valid xml.
I think the simplest aprroach is to wrap
new XmlDocument().LoadXml(strINPUT);
In a try/catch.
The problem im facing is, sometimes strINPUT is an html file, if the header of this file contains
<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xml:lang=""en-GB"" xmlns=""http://www.w3.org/1999/xhtml"" lang=""en-GB"">
...like many do, it actually tries to make a connection to the w3.org url, which i really dont want it doing.
Anyone know if its possible to just parse the string without trying to be clever and checking external urls? Failing that is there an alternative to xmldocument?
Try the following:
XmlDocument doc = new XmlDocument();
using (var reader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings() {
ProhibitDtd = true,
ValidationType = ValidationType.None
})) {
doc.Load(reader);
}
The code creates a reader that turns off DTD processing and validation. Checking for wellformedness will still apply.
Alternatively you can use XDocument.Parse if you can switch to using XDocument instead of XmlDocument.
I am not sure about the reason behind the problem but Have you tried XDocument and XElement classes in System.Xml.Linq
XDocument document = XDocument.Load(strINPUT , LoadOptions.None);
XElement element = XElement.Load(strINPUT );
EDIT: for xml as string try following
XDocument document = XDocument.Parse(strINPUT , LoadOptions.None );
Use XmlDocument's load method to load the xml document, use XmlNodeList to get at the elements, then retrieve the data ...
try the following:
XmlDocument xmlDoc = new XmlDocument();
//use the load method to load the XML document from the specified stream.
xmlDoc.Load("myXMLDoc.xml");
//Use the method GetElementsByTagName() to get elements that match the specified name.
XmlNodeList item = xDoc.GetElementsByTagName("item");
XmlNodeList url = xDoc.GetElementsByTagName("url");
Console.WriteLine("The item is: " + item[0].InnerText));
add a try/catch block around the above code and see what you catch, modify your code to address that situation.

Categories

Resources