Get xml node value as string C# - c#

I've been trying to pull the value of the XML node into a string. Here is what the XML looks like:
<currentvin value="1FTWW31R08EB18119" />
I can't seem to figure out how to grab that value. I didn't write this XML, by the way. So far I have tried several approaches, including the following:
public void xmlParse(string filePath)
{
XmlDocument xml = new XmlDocument();
xml.Load(filePath);
XmlNode currentVin = xml.SelectSingleNode("/currentvin");
string xmlVin = currentVin.Value;
Console.WriteLine(xmlVin);
}
Which doesn't work. I then tried:
public void xmlParse(string filePath)
{
XmlDocument xml = new XmlDocument();
xml.Load(filePath);
string xmlVin = xml.SelectSingleNode("/currentvin").Value;
Console.WriteLine(xmlVin);
}
But that doesn't work either. I am getting a null reference exception stating that Object reference not set to an instance of an object. Any ideas?

I think you're confusing the Value property of the XmlNode class, with an XML attribute named "value".
value is an attribute in your xml so either modify your xpath query to be
xml.SelectSingleNode("/currentvin/#value").Value
Or user the Attributes collection of the selected XmlNode.

You are looking for the value of the attribute "value" (that's a handful) not the value of the node itself - so you have to use the Attribute property:
string xmlVin = xml.SelectSingleNode("/currentvin").Attributes["value"].Value;
Or in the first version:
XmlNode currentVin = xml.SelectSingleNode("/currentvin");
string xmlVin = currentVin.Attributes["value"].Value;

If your entire XML contains only this node then it could be xml.DocumentElement.Attributes["value"].Value;

Related

How to get the xml node value into a string

How to get the xml node value in a string.
i am getting This error
Data at the root level is invalid. Line 1, position 1.
error shown in this line
xmldoc.LoadXml(xmlFile);
my xml
<?xml version="1.0" encoding="utf-8" ?>
<UOM>
<!-- The selected currency used will be stored here for Code reference" -->
<ActiveCurrencyType>
<ActiveCurrency>U.S.Dollar</ActiveCurrency>
<ActiveCode>USD</ActiveCode>
<ActiveSymbol>$</ActiveSymbol>
</ActiveCurrencyType>
<!-- The selected Dimension used will be stored here for Code reference -->
<ActiveDimension>
<ActiveDimensionUOM>Inches</ActiveDimensionUOM>
<ActiveDimensionSymbol>.in</ActiveDimensionSymbol>
</ActiveDimension>
<!-- The selected weight used will be stored here for Code reference -->
<ActiveWeight>
<ActiveWeightUOM>Pounds</ActiveWeightUOM>
<ActiveWeightSymbol>lb</ActiveWeightSymbol>
</ActiveWeight>
</UOM>
C# code
string xmlFile = Server.MapPath("~/HCConfig/HCUOM.xml");
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlFile);
XmlNodeList nodeList = xmldoc.GetElementsByTagName("ActiveDimensionSymbol");
string ActiveDimensionSymbol = string.Empty;
foreach (XmlNode node in nodeList)
{
ActiveDimensionSymbol = node.InnerText;
}
How can I achieve this?
You're using the wrong overload, LoadXml doesn't do what you think it does.
Use xmldoc.Load(xmFile); because that method takes an file path as input. LoadXml expects an string with xml in it.
The exception is an indicator of that mistake. What is processed is not XML, and a filepath isn't that.
After this changes the string ActiveDimensionSymbol contains .in if I run this locally.
If you want to use LoadXml you should first read your whole file in a string, for example like so:
xmldoc.LoadXml(File.ReadAllText(xmlFile));
but is really only overhead to call File.ReadAllText if there is an method that accepts a file.
You can use the Descendants() method to get all XElements by certain name, found in the System.Xml.Linq namespace.
XDocument doc = XDocument.Load("XMLFile1.xml");
string[] allActiveWeightUOMs = doc.Descendants("ActiveWeightUOM").Select(o => o.Value).ToArray();
// allActiveWeightUOMs : "Pounds" ...
As can seen here link the method that you are using to load the XML excepts xml by string not xml file. You can use XmlDocument.Load instead of XmlDocument.LoadXml
Try this code its works just fine with this xml
string xmlFile = Server.MapPath("~/HCConfig/HCUOM.xml");
XDocument doc = XDocument.Load(xmlFile );
var nodeList = doc.Descendants("ActiveDimensionSymbol");
string ActiveDimensionSymbol = string.Empty;
foreach (var node in nodeList)
{
ActiveDimensionSymbol = node.Value;
}

Pulling string from xml

The xml is coming from a url and all I need is the pull the string "N0014E1" from it. I am not sure why this code is not working. I put a try block around it and I get a "Data root level is invalid"
xml:
<obj is="c2g:Network " xsi:schemaLocation="http://obix.org/ns/schema/1.0/obi/xsd" href="http://192.168.2.230/obix/config/">
<ref name="N0014E1" is="c2g:LOCAL c2g:Node"xsi:schemaLocation="http://obix.org/ns/sc/1.0/obix/xsd" href="N0014E1/"></ref>
</obj>
C# code:
public static string NodePath = "http://" + MainClass.IpAddress + ObixPath;
public static void XMLData()
{
XmlDocument NodeValue = new XmlDocument();
NodeValue.LoadXml(NodePath);
var nodes = NodeValue.SelectNodes(NodePath);
foreach (XmlNode Node in nodes)
{
HttpContext.Current.Response.Write(Node.SelectSingleNode("//ref name").Value);
Console.WriteLine(Node.Value);
}
//Console.WriteLine(Node);
Console.ReadLine();
}
Your SelectNodes and SelectSingleNode commands are incorrect. Both expect an xpath string to identify the node.
Try the following
string xml = #"<obj is=""c2g:Network "" href=""http://192.168.2.230/obix/config/""><ref name=""N0014E1"" is=""c2g:LOCAL c2g:Node"" href=""N0014E1/""></ref></obj>";
XmlDocument NodeValue = new XmlDocument();
NodeValue.LoadXml(xml);
XmlNode r = NodeValue.SelectSingleNode("//ref[#name]");
if (r != null)
{
System.Diagnostics.Debug.WriteLine(r.Attributes["name"].Value);
}
Also, Note, that LoadXml method simply loads an xml string; it will not load from a remote url.
As #kevintdiy has pointed out your xml is not entirely correct. In the sample above I have stripped out the xsi reference as you are lacking a definition for it.
If you have access to the source xml, either remove the reference to xsi if its not required or add a definition for it to the root node.
If this is not possible, then you may want to consider using regular expression or other string based methods for getting the value.

Get value from node with same name

I'd like to retrieve information from an XML file, however the way it's formatted is pretty strange. Here it is...
<?xml version="1.0"?>
<Careers>
<CareerList>
<CareerName></CareerName>
<CareerDescription></CareerDescription>
</CareerList>
<CareerList>
<CareerName>Cook</CareerName>
<CareerDescription>Cooks food for people</CareerDescription>
</CareerList>
</Careers>
I'd like to get the 2nd value, which would be Cook and the description which is Cooks food for people, but instead I'm getting only the empty node. For example...
public string CareerDescription(string CareerFile)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CareerFile);
string Description = xmlDoc.SelectSingleNode("Careers/CareerList/CareerDescription").InnerText;
return Description;
}
How would I select the second node instead of the first?
You can use an index in your XPath expression:
xmlDoc.SelectSingleNode("Careers/CareerList[2]/CareerDescription").InnerText
Personally I'd use LINQ to XML instead, mind you:
var doc = XDocument.Load(CareerFile);
return doc.Root
.Elements("CareerList")
.ElementAt(1) // 0-based
.Element("CareerDescription")
.Value;
Instead of SelectSingleNode you should use SelectNodes: it will return XmlNodeList nodeList. Then you should take the InnerText of the element from that node list with index [1];
public string CareerDescription(string CareerFile)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(CareerFile);
string Description = xmlDoc.SelectNodes("Careers/CareerList/CareerDescription")[1].InnerText;
return Description;
}
Refer to the documentation on this method on MSDN for more details: http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes%28v=vs.71%29.aspx
Just a straight way of LINQ to XML routine (and because it is LINQ, I prefer this way much more than the "standard" usage of XmlDocument with the support of XPath):
return XDocument.Load(CareerFile)
.Descendants("CareerDescription").Skip(1).First().Value;

Reading values from within an XNode

I have some code that is returning a XNode to me which looks like this:
<File>
<Component>Main</Component>
<Path>C:\Main\</Path>
<FileName>main.txt</FileName>
</File>
I need to have some C# code that will be able to pull out the value of Path for example (C:\Main). I know that if I was using an XML node I could do it like this:
String filePath = xmlNode["Path"].InnerText;
Does anybody know what the equivalent would be for an XNode? Any help is much appreciated!
Do you have to have it returning an XNode rather than an XElement? With an XElement it's simpler than with an XNode:
string filePath = fileElement.Element("Path").Value;
That will find the first Path element, and will throw a NullReferenceException if there aren't any. An alternative if you're happy to get null if there aren't any would be:
string filePath = (string) fileElement.Element("Path");
If you're really stuck with XNode, you'll either have to cast to XElement or possibly XContainer.
You can convert your XNode into XElement to access to its properties, my example:
XNode lastNode = myXElement.LastNode;
//if I want to get the 'ID' attribute
string id = (lastNode as XElement).Attribute("ID").Value;
Casting XNode to XElement works for the individual element to retrieve its value or attributes. But you won't be able to use myXelement.Elements("XXX") to get nested elements. For that you can use xmlNode.Nodes().
This should work:
var nodes = xmlNode.Nodes();//Get all nodes under 'File'
var fileNameNode = nodes.Where(el => ((XElement)el).Name.LocalName == "FileName")
.FirstOrDefault();
string filePath = ((XElement)fileNameNode).Value;
You may use this:
XElement xtr = XElement.Load("path/to/your/xml/file");
String filePath = xtr.Descendants("Path").Single().Value;
If you import System.Xml.XPath you can use XPathSelectElement like this on the XNode object:
String component = xmlNode.XPathSelectElement("Component");
String path = xmlNode.XPathSelectElement("Path");
String fileName = xmlNode.XPathSelectElement("FileName");
It depends on what convcrete objets is the abstract XNode. From XNode Class:
XNode is an abstract common base class for the following types:
XComment
XContainer: can be XDocument or XElement
XDocumentType
XProcessingInstruction
XText
So you need to check if you can cast it to an XDocument or an XElement, and use their methods, or use LINQ to XML:
For example:
Best way to query XDocument with LINQ?
Querying an XDocument vs. Querying an XElement (C#)
XNode xnode
string value = (xnode as XElement).Value;
we can get the value form XElement object so we need to cast XNode to XElement first
should work

Extract contents from XML file

I have a C# application that uses a button to generate a file. Currently, I want to use C# to extract out contents from the XML file and pass it as a string. For example in my XML file, I have a tag name. I want to use c# to extract the name from the XML file. How should I go about achieving it? Below is the sample code I have currently. The entire process must be carried out using a button click.
private void button1_Click(object sender, EventArgs e)
{
XElement xml = XElement.Load("C:\\Windows 7.xml");
IEnumerable<XElement> propertyIDs = xml.Descendants("PropertyId");
foreach (XElement child in xml.Elements())
{
XElement row = child.Element("my:VM_Name");
string test = xml.ToString();
Console.WriteLine(test);
}
}
Please access this link to view my xml file: http://pastebin.com/NKhBb4Zh
I rewrote your example and changed it to make use of the XmlDocument class. As there is the my Namespace I had to add a NameSpaceManager. using this you may even select a spefic node.
string url = #"e:\temp\data.xml";
XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(url);
XmlElement docElement = doc.DocumentElement;
/// loop through all childNodes
foreach (XmlNode childNode in docElement.ChildNodes)
{
Console.WriteLine(childNode.Name + ": " + childNode.InnerText);
}
XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-05-27T03:57:48");
/// use the given XmlNamespaceManager to select a specific element
XmlNode node = docElement.SelectSingleNode("my:VM_DiskSize", mgr);
/// use innerText for node text and value for attributes only
Console.WriteLine("\n" + node.Name + ": " + node.InnerText);
hth
The comments you added to your question were very helpful. In particular:
I added this code:
XElement name = xml.Element("my:VM_Name");
string test = xml.ToString();
Console.WriteLine(test);
But I am still unable to extract out Windows 7 from the XML tag
And:
i get this error The ':' character, hexadecimal value 0x3A, cannot be included in a name.
Let's start with the error first. You cannot pass to the Element method an ns:name pair as you've done. With this API, the namespace (ns) must be supplied programatically via the XName type. So instead, that line should read:
XElement name = xml.Element(XName.Get("VM_Name", "my"));
Here we pass the qualified name as an actual XName and not as a colon-delimited string as it originates. Pay attention to the order; the namespace comes second using this syntax.
Now, once you have done all this, the other line in which you have a problem is:
string test = xml.ToString();
Here, xml refers to your root XML node whereas what you actually want is, presumably, the element for which you just queried: xml.Element(XName.Get("VM_Name", "my")). Furthermore, to get the text contents of that node, you should use the Value property. I suspect what you really want is:
string test = name.Value;

Categories