XML Filtering in C#

xml Sri Lanka
  • 15 years ago
    I have a XML document, formated like this;

    <root>

    <template>
    <templateid>1</templateid>
    <name>first</name>
    </template>

    <template>
    <templateid>2</templateid>
    <name>second</name>
    </template>

    i need to filter this based on the 'templtaeid', i used the following method.


    public void LoadPreview(string id)
    {
     string url = Server.MapPath("../")+"\\XML\\Templates.xml";
     DataSet MainDataSet = new DataSet();
     MainDataSet.ReadXml(url);
     DataRow[] rows = MainDataSet.Tables[0].Select("templateid="+id);
     DataTable MainDataTable = MainDataSet.Tables[0].Clone();
     foreach (DataRow row in rows)
     {
       MainDataTable.ImportRow(row);
     }
     Label1.Text=MainDataTable.Rows[0].ItemArray[1].ToString();

    }


    it filters the xml elements for some template ids. For example it always giving the error "There is no row at position 0." for <templateid>43</templateid> , except that all other templateids are working.

    When i change the <templateid>2</templateid> as <templateid>400</templateid> then it works, but <templateid>4</templateid> starts to give troubles.

    i got a solution for this as well. that is :


    <root>

    <template id="1">
    <templateid>1</templateid>
    <name>first</name>
    </template>

    <template id="2">
    <templateid>2</templateid>
    <name>second</name>
    </template>



    public void LoadPreview(string templateID)
    {
     //Open XML file
     string xmlFilePath = Server.MapPath("../") + "\\XML\\Templates.xml";
     FileStream fs = new FileStream(xmlFilePath,FileMode.Open,FileAccess.Read,
     FileShare.ReadWrite);
     XmlDocument xmldoc = new XmlDocument();
     xmldoc.Load(fs);
     XmlNodeList xmlnode = xmldoc.GetElementsByTagName("template");            
               
     //Loading the control from XML file
     int iNodeCount = xmlnode.Count;
     for (int i = 0; i<iNodeCount; i++)
     {
       if (templateID.Trim() == xmlnode.ChildNodes[0].FirstChild.InnerText)
       {
         PreviewSelection.ImageUrl=xmlnode.ChildNodes[2].FirstChild.InnerText;
       }
     }
    }

    but can anyone explain me, what wrong with my first method ?

Post a reply

No one has replied yet! Why not be the first?

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The greatest performance improvement of all is when a system goes from not-working to working.” - John Ousterhout