I am using C# XmlDocument API.
I have the following XML:
<Node1>
<Node2>
<Node3>
</Node3>
</Node2>
</Node1>
I want to get Node3 as an XmlNode. But my code is returning null:
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNode root_node = doc.DocumentElement.SelectSingleNode("/Node1");
Log(root_node.OuterXml);
XmlNode test_node = root_node.SelectSingleNode("/Node2/Node3");
if (test_node == null)
Logger.Log.Error(" --- TEST NODE IS NULL --- ");
The log for root_node.OuterXml logs
<Node1><Node2><Node3>.....
But test_node returns null.
What is going wrong here?
Use the path "Node2/Node3" instead of "/Node2/Node3":
XmlNode test_node = root_node.SelectSingleNode("Node2/Node3");
In an XPath expression, a leading forward slash / represents the root of the document. The expression "/Node2/Node3" doesn't work because <Node2> isn't at the root of the document.
Use // instead of /, when you are selecting from the root node
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNode root_node = doc.DocumentElement.SelectSingleNode("/Node1");
XmlNode test_node = root_node.SelectSingleNode("//Node2/Node3");
Another option is to use full path to the node 3
XmlNode test_node = doc.DocumentElement.SelectSingleNode("/Node1/Node2/Node3");
You can simple call Descendants()
var xml= #"<Node1><Node2><Node3></Node3></Node2></Node1>";
XDocument doc = XDocument.Parse(xml);
var node = doc.Descendants("Node3");
or use Element() starting from Root
var node2= doc.Root.Element("Node2").Element("Node3");
or use XPathSelectElement()
var node3= doc.XPathSelectElement("/Node1/Node2/Node3");
Related
I want to replace following #eleval2,#eleval4 parameters with some other values using c#.net.Please help me to do it.
<root>
<element1>
<element2>
#eleval2
</element2>
</element1>
<element3>
<element4>
<element4>
#eleval4
</element4>
</element4>
</element3>
Directly updating node:
XmlDocument xml = new XmlDocument();
xml.Load("file_name.xml");
xml.SelectSingleNode("/root/element1/element2").InnerText = "NewValue";
For looping:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("path_here");
XmlNodeList tagNodes= xmlDoc.GetElementsByTagName("tag_of_your_interest");
//Loop through first child of above list
foreach (XmlNode chapter in tagNodes[0].ChildNodes)
{
//Perform your updates here
}
Load from string:
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Get all list of nodes matches path:
XmlNodeList xnList = doc.SelectNodes("/sections/notebooks/article");
I need to get node value from xml. The xml has namespace.
I have the following code
string xml =
"<file xmlns=\"SFAKT\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<document>test</document>" +
"</file>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDocument.NameTable);
ns.AddNamespace("sf", "SFAKT");
XmlNode node = xmlDocument.SelectSingleNode("sf:file/document");
But node = null
Can you tell me where is the error in my code?
You need to use the overloaded SelectSingleNode method and pass in the XmlNamespaceManager. Also, you need the sf prefix for the document node.
Pull the node out like this:
XmlNode node = xmlDocument.SelectSingleNode("sf:file/sf:document", ns);
I have this XML at http://localhost/file.xml:
<?xml version="1.0" encoding="utf-8"?>
<val:Root xmlns:val="http://www.hw-group.com/XMLSchema/ste/values.xsd">
<Agent>
<Version>2.0.3</Version>
<XmlVer>1.01</XmlVer>
<DeviceName>HWg-STE</DeviceName>
<Model>33</Model>
<vendor_id>0</vendor_id>
<MAC>00:0A:DA:01:DA:DA</MAC>
<IP>192.168.1.1</IP>
<MASK>255.255.255.0</MASK>
<sys_name>HWg-STE</sys_name>
<sys_location/>
<sys_contact>
HWg-STE:For more information try http://www.hw-group.com
</sys_contact>
</Agent>
<SenSet>
<Entry>
<ID>215</ID>
<Name>Home</Name>
<Units>C</Units>
<Value>27.7</Value>
<Min>10.0</Min>
<Max>40.0</Max>
<Hyst>0.0</Hyst>
<EmailSMS>1</EmailSMS>
<State>1</State>
</Entry>
</SenSet>
</val:Root>
I am trying to read this from my c# code:
static void Main(string[] args)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load("http://localhost/file.xml");
XmlElement root = xmlDoc.DocumentElement;
// Create an XmlNamespaceManager to resolve the default namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("val", "http://www.hw-group.com/XMLSchema/ste/values.xsd");
XmlNodeList nodes = root.SelectNodes("/val:SenSet/val:Entry");
foreach (XmlNode node in nodes)
{
string name = node["Name"].InnerText;
string value = node["Value"].InnerText;
Console.Write("name\t{0}\value\t{1}", name, value);
}
Console.ReadKey();
}
}
Problem is that the node is empty. I understand this is a common newbie problem when reading XML, still not able to solve what I am doing wrong, probably something with the Namespace "val" ?
You need to pass the namespace manager into the SelectNodes()
method.
Edit: corrected code
XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);
Just change you Xpath to:
XmlNodeList nodes1 = root.SelectNodes("/val:Root/SenSet/Entry",nsmgr);
Or:
XmlNodeList nodes = root.SelectNodes("SenSet/Entry");
Your xpath query string should be:
XmlNodeList nodes = root.SelectNodes("/val:Root/SenSet/Entry", nsmgr);
or more concisely,
XmlNodeList nodes = root.SelectNodes("//SenSet/Entry", nsmgr);
I have XML stored in string variable:
<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>
Here I want to change XML tag <ItemMasterList> to <Masterlist>. How can I do this?
System.Xml.XmlDocument and the associated classes in that same namespace will prove invaluable to you here.
XmlDocument doc = new XmlDocument();
doc.LoadXml(yourString);
XmlDocument docNew = new XmlDocument();
XmlElement newRoot = docNew.CreateElement("MasterList");
docNew.AppendChild(newRoot);
newRoot.InnerXml = doc.DocumentElement.InnerXml;
String xml = docNew.OuterXml;
I know i am a bit late, but just have to add this answer as no one seems to know about this.
XDocument doc = XDocument.Parse("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>");
doc.Root.Name = "MasterList";
Which returns the following:
<MasterList>
<ItemMaster>
<fpartno>xxx</fpartno>
<frev>000</frev>
<fac>Default</fac>
</ItemMaster>
</MasterList>
You can use LINQ to XML to parse the XML string, create a new root and add the child elements and attributes of the original root to the new root:
XDocument doc = XDocument.Parse("<ItemMasterList>...</ItemMasterList>");
XDocument result = new XDocument(
new XElement("Masterlist", doc.Root.Attributes(), doc.Root.Nodes()));
Using the XmlDocument way, you can do this as follows (and keep the tree intact):
XmlDocument oldDoc = new XmlDocument();
oldDoc.LoadXml("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>");
XmlNode node = oldDoc.SelectSingleNode("ItemMasterList");
XmlDocument newDoc = new XmlDocument();
XmlElement ele = newDoc.CreateElement("MasterList");
ele.InnerXml = node.InnerXml;
If you now use ele.OuterXml is will return: (you you just need the string, otherwise use XmlDocument.AppendChild(ele) and you will be able to use the XmlDocument object some more)
<MasterList>
<ItemMaster>
<fpartno>xxx</fpartno>
<frev>000</frev>
<fac>Default</fac>
</ItemMaster>
</MasterList>
As pointed by Will A, we can do it that way but for case where InnerXml equals the OuterXml the following solution will work out:
// Create a new Xml doc object with root node as "NewRootNode" and
// copy the inner content from old doc object using the LastChild.
XmlDocument docNew = new XmlDocument();
XmlElement newRoot = docNew.CreateElement("NewRootNode");
docNew.AppendChild(newRoot);
// The below line solves the InnerXml equals the OuterXml Problem
newRoot.InnerXml = oldDoc.LastChild.InnerXml;
string xmlText = docNew.OuterXml;
My code doesn't return the node
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNode node_ = xml.SelectSingleNode(node);
return node_.InnerText; // node_ = null !
I'm pretty sure my XML and Xpath are correct.
My Xpath : /ItemLookupResponse/OperationRequest/RequestId
My XML :
<?xml version="1.0"?>
<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
<OperationRequest>
<RequestId>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx</RequestId>
<!-- the rest of the xml is irrelevant -->
</OperationRequest>
</ItemLookupResponse>
The node my XPath returns is always null for some reason. Can someone help?
Your XPath is almost correct - it just doesn't take into account the default XML namespace on the root node!
<ItemLookupResponse
xmlns="http://webservices.amazon.com/AWSECommerceService/2005-10-05">
*** you need to respect this namespace ***
You need to take that into account and change your code like this:
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("x", "http://webservices.amazon.com/AWSECommerceService/2005-10-05");
XmlNode node_ = xml.SelectSingleNode(node, nsmgr);
And then your XPath ought to be:
/x:ItemLookupResponse/x:OperationRequest/x:RequestId
Now, your node_.InnerText should definitely not be NULL anymore!
Sorry for the late reply but I had a similar problem just a moment ago.
if you REALLY want to ignore that namespace then just delete it from the string you use to initialise the XmlDocument
text=text.Replace(
"<ItemLookupResponse xmlns=\"http://webservices.amazon.com/AWSECommerceService/2005-10-05\">",
"<ItemLookupResponse>");
XmlDocument xml = new XmlDocument();
xml.InnerXml = text;
XmlNode node_ = xml.SelectSingleNode(node);
return node_.InnerText;