Hi,

I am wondering if anyone on the list could help me search an xml file based on the user input. Right now, I have two separate files, one that shows all the data from an xml file, and the other is a simple web form with a button like the code from the link http://www.w3schools.com/aspnet/showasp.asp?filename=demo_textbox.

Can anyone provide some ideas on how I can search an xml based on the user input and have that displayed?

Thanks for your help.

Recommended Answers

All 23 Replies

All depends on what you want to search in the xml file, could your provide a short sample of what your xml looks like?

There is more to this, but I am posting one portion here:

<music_songs>
<song>
  <title>(I Just) Died In Your Arms</title>
  <category>Rock</category>
  <album>80 Popular Hits</album>
  <artist>Cutting Crew</artist>
  <date added="03-24-2009"/>
</song>
</music_songs>

Thanks for your help.

string search = txtSearch.Text;
XmlDocument xmldoc = new XmlDocument(filepath);

List<XmlNode> results = new List<XmlNode>();
foreach(XmlNode node in xml.SelectNodes("//*")
{
    if(node.InnerXml.Contains(search))
    {
        results.Add(node);
    }
}

PierlucSS : good one sir..

The snippet you provided, does it have to be in sub?
The following is not my eventual goal, but I think this example may help me understand how to use the portion you provided in a search with existing xml data:

<script  runat="server">
Sub submit(sender As Object, e As EventArgs)
   mess.Text="You selected " & drop1.SelectedItem.Text
End Sub

/*string search = DropDownList1.SelectedItem.Text;
XmlDocument xmldoc = new XmlDocument(alice_music_list2.xml);

List<XmlNode> results = new List<XmlNode>();
foreach(XmlNode node in xml.SelectNodes("//*")
{
    if(node.InnerXml.Contains(search))
    {
        results.Add(node);
    }
}*/
</script>

<html>
<body>

<form runat="server">
   
<asp:DropDownList id="drop1" runat="server">
<asp:ListItem>Rock</asp:ListItem>
<asp:ListItem>Blues</asp:ListItem>
<asp:ListItem>Soft and Laidback</asp:ListItem>
<asp:ListItem>Light Rock</asp:ListItem>
</asp:DropDownList>
<asp:Button Text="Submit" OnClick="submit" runat="server"/>
<p><asp:label id="mess" runat="server"/></p>
</form>
</body>
</html>

The portion I commented out is what you provided, and I edited it a little, is it possible to incorporate it in a way that mess.txt can print out the "result?"

Thanks for your help.

Well you are in the wrong forum because you are using VB.NET, however it is easily convertable.

Next thing, it is bad practice to add vb.net or c# code in the .aspx file you should put in the code behind .aspx.cs or .aspx.vb. If you go on the design model of your website and you double click on a control it should automaticly open up the "code view" and this is where that code should go. all the code need to be wrapped in a

if(IsPostBack)

so it only execute the code after the page is reloaded(which means after you pressed yoru submit button.

So basicly move your sub to code behind, and easy way of doing this is copying it and right clicking in the asp.net code (the one shown up there) and clicking view code.

You should use c# because it owns but here's the vb.net code (Approximate)

Dim xmldoc As XmlDocument = new XmlDocument(alice_music_list2.xml)
Dim results As List(Of XmlNode) = new List(Of XmlNode)

ForEach XmlNode node in xml.SelectNodes("//*")
  
     If node.InnerXml.Contains(search)
           results.Add(node)
     EndIf

Next

Hi,

For some reason, I must have missed something here again. I get an error of:

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30002: Type 'XmlDocument' is not defined.

And, here is the code, which I am pretty sure it is still problematic:

<script  runat="server">

Sub submit(sender As Object, e As EventArgs)
  Dim xmldoc As XmlDocument = new XmlDocument(alice_music_list2.xml)
  Dim results As List(Of XmlNode) = new List(Of XmlNode)

ForEach XmlNode node in xml.SelectNodes("//*")
  
     If node.InnerXml.Contains(search)
           results.Add(node)
     EndIf

Next

   mess.Text="Here are your results: " &results + "You selected " & drop1.SelectedItem.Text 
End Sub

</script>

<html>
<body>

<form runat="server">
   
<asp:DropDownList id="drop1" runat="server">
<asp:ListItem>Rock</asp:ListItem>
<asp:ListItem>Blues</asp:ListItem>
<asp:ListItem>Soft and Laidback</asp:ListItem>
<asp:ListItem>Light Rock</asp:ListItem>
</asp:DropDownList>
<asp:Button Text="Submit" OnClick="submit" runat="server"/>
<p><asp:label id="mess" runat="server"/></p>

</form>

</body>
</html>

Thanks for your help.

P.S. Does anyone know any good ASP.NET tutorials, guides, or books? The W3School's version of ASP.NET 2 tutorial, and it does not seem to be sufficient with what I am trying to accomplish here. Or, does it?

For books, I love "the expert's voice", it's awesome. Look for that on amazon.

And Like I said, your <script runat="server"> should not be there, this code should be in the codeview.

Hi,

Now I am getting really confused.

All that code I have posted is not what have in the html view, but the code I have now in script runat="server", if I don't put it where I have now, where is a good place to put it? An external file?

Thanks for your help.

Hi,

Now I am getting really confused.

All that code I have posted is not what have in the html view, but the code I have now in script runat="server", if I don't put it where I have now, where is a good place to put it? An external file?

Thanks for your help.

if you take a look at your solution explorer and you right click on the current form and then click codeview, this is where it should belong.

And for the error you were getting, that's because you need to import the System.Xml namespace and for the list you will need System.Collections.Generic

Hi,

Thanks for clarifications. I have done some fix ups, and below is my XML:

<music>
<song>
<title>A</title>
<category>Rock</category>
</song>
<song>
<title>A Song</title>
<category>Light Rock</category>
</song>
</music>

Here is my updated code, and my drop down menu is giving me stuff the way I want it, but looks like there is something going on in the actions after that.
Here is the code:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.XML" %>

<script  runat="server">

   Sub submit(ByVal sender As Object, ByVal e As EventArgs)
               
    mess.Text = "You selected " & drop1.SelectedItem.Text  
    Dim file As String = Context.Server.MapPath("music.xml")  
    Dim document As XmlDocument = New XmlDocument()  
    document.Load(file)  
    Dim element As XmlNode = document.SelectSingleNode("/music/song/[category=" + drop1.SelectedItem.Text + "]")
    mess.Text &= element.InnerText  
 End Sub

</script>

<html>
<body>

<form runat="server">
   
<asp:DropDownList id="drop1" runat="server">
<asp:ListItem>Rock</asp:ListItem>
<asp:ListItem>Blues</asp:ListItem>
</asp:DropDownList>
<asp:Button Text="Submit" OnClick="submit" runat="server"/>
<p><asp:label id="mess" runat="server"/></p>

</form>

</body>
</html>

When I push the submit button after making a selection, I get this error on the screen:

Expression must evaluate to a node-set.

Description:
An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the error and
where it originated in the code.

Exception Details:
System.Xml.XPath.XPathException: Expression must evaluate to a node-set.

Looks like I have some errors in my xpath declaration, but I did check the pattern out on the XPath tutorials. Is there something I have done wrong here?

Thanks for your help.

well the problem is your xpath. You are not reffering to any element the way your doing it and tahts why it gives you an error, it should be something like this:

"/music/song/category[text()=whatever]"

Hi,

I have followed your suggestions and made this change to the xpath syntax, since the variable is used by the code to capture user input:

Dim element As XmlNode = document.SelectSingleNode("/musics/song/category[text()=" & drop1.SelectedItem.Text & "]")

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

I believe I did the processing for the concatenation strings correctly, or is it not?
Thanks for your help.

its not "musics" but music (according to what you provided us at the top.

its not "musics" but music (according to what you provided us at the top.

Sorry, that was my typo. Here is the correct code snippet:

Dim element As XmlNode = document.SelectSingleNode("/music/song/category[text()=" & drop1.SelectedItem.Text & "]")

Found that I have an XPath error, which I got it fixed, and yet I still get no result on the nodes I was looking for. I get this as my output after selecting Rock from the drop down menu:

You selected RockRock

Is it possible that I could get the nodes and not another "Rock" in my output?
I also noticed that it has been indicated as selectSingleNode, and I am wondering if I can use something like select all the nodes, but I don't think I could find its function.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.XML" %>

<script  runat="server">

   Sub submit(ByVal sender As Object, ByVal e As EventArgs)
              
    mess.Text = "You selected " & drop1.SelectedItem.Text 
    Dim file As String = Context.Server.MapPath("alice_music_list2.xml") 
    Dim document As XmlDocument = New XmlDocument() 
    document.Load(file) 
    Dim element As XmlNode = document.SelectSingleNode("/music_songs/song/category[text()='" & drop1.SelectedItem.Text & 

"']")
    mess.Text &= element.InnerText 
 End Sub

</script>

<html>
<body>

<form runat="server">
  
<asp:DropDownList id="drop1" runat="server">
<asp:ListItem>Rock</asp:ListItem>
<asp:ListItem>Blues</asp:ListItem>
</asp:DropDownList>
<asp:Button Text="Submit" OnClick="submit" runat="server"/>
<p><asp:label id="mess" runat="server"/></p>

</form>
</body>
</html>

Can anyone on the list please kindly provide some insights on this?
Thanks for your help.

well if you use the code I initialy provided you, thats why I didnt use a more complex xpath, its to go through every nodes and to use contains instead of = (if im not mistaken there is contains in xpath but youd need to google for that)

well if you use the code I initialy provided you, thats why I didnt use a more complex xpath, its to go through every nodes and to use contains instead of = (if im not mistaken there is contains in xpath but youd need to google for that)

Yes, I did go back to one of your earlier posts, but I remembered that it is written in a different kind of .Net language. However, I did try it out, and I would like to know how to look for the entire node that the "category" is the one that the user picks from the drop down menu.

Suppose the user picks "Rock", so I come up with this, (I stripped other parts out or this code is going out of control).

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.XML" %>

<script runat="server">
Sub Page_Load() 

  Dim file As String = Context.Server.MapPath("alice_music_list2.xml") 
  Dim document As XmlDocument = New XmlDocument() 
  document.Load(file) 
  XmlNodeList formatted = document.SelectSingleNode("/music_songs/song/category[text()='Rock']");
  foreach(XmlNode node in formatted) tb1.text +=  node.InnerText + "<br />";
		
end Sub
</script>

<html>
<body>

<form runat="server">
<asp:TextBox id="tb1" runat="server" />
</form>
</body>
</html>

I still get an error telling me
BC30108: 'XmlNodeList' is a type and cannot be used as an expression.

Is there anything wrong with what I have done here?
Thanks again.

well you are selecting a single node and adding it to a collection of nodes. it should be document.SelectNodes

well you are selecting a single node and adding it to a collection of nodes. it should be document.SelectNodes

I think I am getting close. Well, I may be needed to be reminded that I am writing in VB.NET here, right?

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.XML" %>

<script runat="server">
Sub Page_Load() 

  Dim file As String = Context.Server.MapPath("alice_music_list2.xml") 
  Dim document As XmlDocument = New XmlDocument() 
  document.Load(file) 
  Dim nodeList As XmlNodeList 
  nodelist = document.SelectNodes("/music_songs/song/category[text()='Rock']")  
  tb1.text +=  & nodelist & "<br />"
		
end Sub
</script>
<html>
<body>

<form runat="server">
<div>
<asp:TextBox id="tb1" runat="server" /></div>
</form>
</body>
</html>

All seems to be in good shape, except I am getting this error saying

Compiler Error Message: BC30452: Operator '&' is not defined for types 'System.Xml.XmlNodeList' and 'String'.

What is the equivalent of += in the language I am supposed to be working with here? I tried &, and it does not seem to work either.

Thanks for your help.

Well this is totally wrong you cannnot simply concatenate a xmlnodelist. You need to go through each item in a foreach and then select a specific, element, attribute or text

Well this is totally wrong you cannnot simply concatenate a xmlnodelist. You need to go through each item in a foreach and then select a specific, element, attribute or text

Thanks for bringing it up, and I have changed the code to the following after mulling it over. Yet, even with this change, I still get errors on null exception, and I don't get all the titles, like I have seen in the example from http://www.w3schools.com/XPath/tryit.asp?filename=try_xpath_select_pricenodes_high.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.XML" %>

<script runat="server">   
Sub Page_Load() 

  Dim file As String = Context.Server.MapPath("music_list2.xml") 
  Dim document As XmlDocument = New XmlDocument() 
  document.Load(file) 

  Dim songList As XmlNodeList 
  songList = document.SelectNodes("/music_songs/song[category='Rock']/*")    

  Dim song As XmlNode
  For Each song In songList
    
    Dim title As XmlNode = song.FirstChild
    songNodesOut.Text &=  "<b>Title:</b> " & title.InnerText & "<br/>"

   
  Next
		
end Sub
</script>

<html>
<body>

<form runat="server">
<div>
<asp:TextBox id="songNodesOut" runat="server" /></div>
</form>
</body>
</html>

Even with this, I still cannot get all the titles that are "categorized" as Rock. Have I done something wrong here?

Thanks for your help.

Oh, I found it,

I can change the code to songList = document.SelectNodes("/music_songs/song[category='Rock']") then I can pull the songs and the authors, attributes.

Thanks for the kind guiding process.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.