XmlNode.SelectNode with multiple attribute - c#

One of my nodes inmy xml file is as follows.
<LOGIN_ID NAME="Kapil">
<SEARCH_ID>Kapil Koli</SEARCH_ID>
<GUID>111</GUID>
<FIRST_NAME>Kapil</FIRST_NAME>
<LAST_NAME>Koli</LAST_NAME>
<EMAIL_ID>kapil#abc.co.in</EMAIL_ID>
<PASSWORD>abc123**</PASSWORD>
</LOGIN_ID>
The code I am using is -
XmlDocument document = new XmlDocument();
document.Load(_XmlFileName);
nodeList = document.SelectNode."USERS/LOGIN_ID[contains(SEARCH_ID,'Kapil')";
nodeList = document.SelectNode."USERS/LOGIN_ID[contains(EMAIL_ID,'kapil#abc.co.in')";
I want to use select node which will accept search_id and login_id as attributes to search?
If either search_id or email_id is wrong, I want to return null.
How could I do this?
thanks.
kapil.

USERS/LOGIN_ID[contains(SEARCH_ID,'Kapil') and contains(EMAIL_ID,'kapil#abc.co.in')]
should do the trick.

Related

Copy Node and change Value of an Attribute

I have the following XML File. I want to copy a new "Test" and change the ID of the Test. How is it possible?
I already can copy the nodes, unfortunately not on the correct position (see images) and I also canĀ“t change the ID.
Anyone have a solution for me?
Before:
After:
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Before.xml");
XmlNode Set = xmldoc.DocumentElement;
string strXmlQuery = "/Toolings/Testing/Test1";
XmlNode NodeToCopy = Set.SelectSingleNode(strXmlQuery);
XmlNode NewNode = NodeToCopy.CloneNode(true);
NodeToCopy.AppendChild(NewNode);
Set.InsertAfter(NewNode, Set.LastChild);
XPathNavigator navigator = xmldoc.CreateNavigator();
navigator.MoveToRoot();
navigator.MoveToFirstChild();
navigator.MoveToFirstChild();
navigator.MoveToFirstChild();
navigator.MoveToFirstChild();
navigator.SetValue("5678");
xmldoc.Save(After.xml");
Here is an example using System.Xml.Linq.XDocument which is a much easier API than XmlDocument:
//You can also use Load(), this is just so I didn't have to make a file
XDocument doc = XDocument.Parse("<Toolings><Testing><Test><ID>1234</ID></Test></Testing></Toolings>");
//Grab the first Test node (change the predicate if you have other search criteria)
var elTest = doc.Descendants().First(d => d.Name == "Test");
//Copy the node, only necessary if you don't know the structure at design time
XElement el = new XElement(elTest);
el.Element("ID").Value = "5678";
//inject new node
elTest.AddAfterSelf(el);
doc.Save("After.xml");

Get xml node using c#

I have a request that returns a large xml file. I have the file in a XmlDocument type in my application. From that Doc how can I read an element like this:
<gphoto:videostatus>final</gphoto:videostatus>
I would like to pull that value final from that element. Also If i have multiple elements as well, can I pull that into a list? thanks for any advice.
If you already have an XmlDocument then you can use the function GetElementsByTagName() to create an XmlNodeList that can be accessed similar to an array.
http://msdn.microsoft.com/en-us/library/dc0c9ekk.aspx
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
//Display all the book titles.
XmlNodeList elemList = doc.GetElementsByTagName("title");
for (int i=0; i < elemList.Count; i++)
{
Console.WriteLine(elemList[i].InnerXml);
}
You can select nodes using XPath and SelectSingleNode SelectNodes. Look at http://www.codeproject.com/Articles/9494/Manipulate-XML-data-with-XPath-and-XmlDocument-C for examples. Then you can use for example InnerText to get final. Maybe you need to work with namespaces (gphoto). The //videostatus would select all videostatus elements
You can try using LINQ
XNamespace ns = XNamespace.Get(""); //use the xmnls namespace here
XElement element = XElement.Load(""); // xml file path
var result = element.Descendants(ns + "videostatus")
.Select(o =>o.Value).ToList();
foreach(var values in value)
{
}
Thanks
Deepu

How to add and delete an XML node?

I have this code below. I want to add a new node in it to hold more user records and if I want I can remove them. Can anyone help me?
string filename = "text.xml";
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Login");
XmlElement id = doc.CreateElement("passWord");
root.SetAttribute("userName", nameTxb.Text);
id.SetAttribute("passWord", passwordTxb.Text);
XmlElement name = doc.CreateElement("UserName");
XmlElement passd = doc.CreateElement("PassWord");
name.InnerText = nameTxb.Text;
passd.InnerText = passwordTxb.Text;
root.AppendChild(name);
root.AppendChild(passd);
doc.AppendChild(root);
doc.Save(filename);
MessageBox.Show("Created SuccesFully!");
this.Close();
Your XML document is stored in variable doc. You may use doc.SelectNodes() to select specified nodes using XPATH. You may also iterate over selected nodes and append childs, remove childs etc.
var nodes = doc.SelectNodes("xpath");
foreach(XmlNode node in nodes)
{
//
}
This will remove an element. You can keep using SelectSingleNode() to move down through the branches of the xml. element can also be selected that way - for this example, just consider it an arbitrary starting point.
someElement.RemoveChild(oDoc.SelectSingleNode("Parent").SelectSingleNode("Child"));
As far as I know, you can also use the same method at the XmlDocument level too.
Hope this helps.

XmlReader Innertext Problem

I have an Xml document in which some of the elements look like this:
<rootNode attib1="qwerty" >
<subNode1>W</subNode1>
<subNode2>X</subNode2>
<subNode3>Y</subNode3>
<subNode4>Z</subNode4>
ABC
</rootNode>
My objective is to get "ABC" out of the above example. I tried looking at the InnerText (which returns "WXYZABC") and InnerXml and Value (which returns null) properties in the XmlElement class and bunch of properties in the XmlReader class too. Somehow I don't see an elegant way to extract the data I need.
Can someone please help me out?
Thanks in advance.
Have a go with this one:
string xml = #"<rootNode attib1=""qwerty"" >
<subNode1>W</subNode1>
<subNode2>X</subNode2>
<subNode3>Y</subNode3>
<subNode4>Z</subNode4>
ABC
</rootNode>";
var xElement = XElement.Parse(xml);
xElement.Elements().Remove();
xElement.Value.Dump();
What it does is remove all the known Elements and that leaves you with the text you are looking for.
Based on the excellent suggestion from #djechelon, I seem to have found a solution to this:
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"D:\Test.xml");
XmlElement xmlElement = xdoc.DocumentElement;
foreach (XmlNode node in xmlElement.ChildNodes)
if (node.NodeType == XmlNodeType.Text
&& !string.IsNullOrWhiteSpace(node.Value))
Console.WriteLine(node.Value.Trim());
The above uses the simple fact that the inner text is also an XmlNode as part of the ChildNodes collection of the XmlElement.
Thanks everyone for the great responses!
Try XmlElement.Value
Edit: This is the wrong approach as this will always return NULL on an element node.

Get content of XML node using c#

simple question but I've been dinking around with it for an hour and it's really starting to frustrate me. I have XML that looks like this:
<TimelineInfo>
<PreTrialEd>Not Started</PreTrialEd>
<Ambassador>Problem</Ambassador>
<PsychEval>Completed</PsychEval>
</TimelineInfo>
And all I want to do is use C# to get the string stored between <Ambassador> and </Ambassador>.
So far I have:
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNode x = doc.SelectSingleNode("/TimelineInfo/Ambassador");
which selects the note just fine, now how in the world do I get the content in there?
May I suggest having a look at LINQ-to-XML (System.Xml.Linq)?
var doc = XDocument.Load("C:\\test.xml");
string result = (string)doc.Root.Element("Ambassador");
LINQ-to-XML is much more friendly than the Xml* classes (System.Xml).
Otherwise you should be able to get the value of the element by retrieving the InnerText property.
string result = x.InnerText;
The InnerText property should work fine for you.
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.innertext.aspx
FWIW, you might consider switching API to linq-to-xml (XElement and friends) as IMHO it's a friendly, easier API to interact with.
System.Xml version (NOTE: no casting to XmlElement needed)
var xml = #"<TimelineInfo>
<PreTrialEd>Not Started</PreTrialEd>
<Ambassador>Problem</Ambassador>
<PsychEval>Completed</PsychEval>
</TimelineInfo>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var node = doc.SelectSingleNode("/TimelineInfo/Ambassador");
Console.WriteLine(node.InnerText);
linq-to-xml version:
var xml = #"<TimelineInfo>
<PreTrialEd>Not Started</PreTrialEd>
<Ambassador>Problem</Ambassador>
<PsychEval>Completed</PsychEval>
</TimelineInfo>";
var root = XElement.Parse(xml);
string ambassador = (string)root.Element("Ambassador");
Console.WriteLine(ambassador);
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNode x = doc.SelectSingleNode("/TimelineInfo/Ambassador");
x.InnerText will return the contents
Try using Linq to XML - it provides a very easy way to query xml datasources - http://msdn.microsoft.com/en-us/library/bb387098%28v=VS.100%29.aspx

Categories