Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find through multiple attributes in XML

I'm trying to search multiple attributes in XML :

<APIS>
  <API Key="00001">
    <field Username="username1" UserPassword="password1" FileName="Filename1.xml"/>
    <field Username="username2" UserPassword="password2" FileName="Filename2.xml"/>
    <field Username="username3" UserPassword="password3" FileName="Filename3.xml"/>
  </API>
</APIS>

I need to check if in the "field" the Username AND UserPassword values are both what I am comparing with my Dataset values, is there a way where I can check multiple attributes (AND condition) without writing my own logic of using Flags and breaking out of loops.

Is there a built in function of XMLDoc that does it? Any help would be appreciated!

like image 269
Murtaza Mandvi Avatar asked Dec 09 '08 19:12

Murtaza Mandvi


2 Answers

To search for what you want in the snippet of XML you provided, you would need the following XPath expression:

/APIS/API/field[@Username='username1' and @UserPassword='password1']

This would either return something, if user name and password match - or not if they don't.

Of couse the XPath expression is just a string - you can build it dynamically with values that were entered into a form field, for example.

If you tell what language/environment you are in, code samples posted here will likely get more specific.

This is a way to do it in C# (VB.NET is analogous):

// make sure the following line is included in your class
using System.Xml;

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("your XML string or file");

string xpath = "/APIS/API/field[@Username='{0}' and @UserPassword='{1}']";
string username = "username1";
string password = "password1";

xpath = String.Format(xpath, username, password);
XmlNode userNode = xmldoc.SelectSingleNode(xpath);

if (userNode != null)
{
  // found something with given user name and password
}
else
{
  // username or password incorrect
}

Be aware that neither user names nor passwords can contain single quotes, or the above example will fail. Here is some info on this peculiarity.

There is also a How-To from Microsoft available: HOW TO: Use the System.Xml.XmlDocument Class to Execute XPath Queries in Visual C# .NET

like image 143
Tomalak Avatar answered Oct 05 '22 12:10

Tomalak


Searching XML is what XPath was made for. You didn't specify what language you're using, but here's an article on processing XML using XPath in Java, and here's one using C#.

like image 33
Bill the Lizard Avatar answered Oct 05 '22 11:10

Bill the Lizard