简体   繁体   中英

How to read a specific XML node?

I have an XML file with data corresponding to multiple objects. I am trying to open the XML file, loop through to find a specific filename and read in all the values associated with that.

Problem:

It never has a match between an XMLElement's Name and the file name. So "I match the currently open file's name" never gets printed.

What I want to happen: So when a "dog.jpg" is opened by a user in the OpenFileDialog, the XML document gets loaded up and it should be able to find the XML element "Name" with the value dog.jpg and print "I match the currently open file's name".

Also, I wanted to know how can I read other corresponding values once I get a match like the different distance values?

Code in my Open method :

string fileName = openFileDialog1.FileName; //file name of a JPEG file opened by a user
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Users\Desktop\TangramsTool\patterndata.xml");
XmlNodeList nodeList = doc.SelectNodes("/Patterns/Pattern");
foreach (XmlNode node in nodeList)
    {
         string text = node["Name"].InnerText; //or loop through its children as well
         if (text.Equals(fileName))
         {
              Console.WriteLine("I match the currently open file's name: " + text);
         }
         else
         {
              Console.WriteLine("This node's name is : " + text);
         }
    }

My XML file:

<Patterns>
     <Pattern> 
         <Name>dog.jpg</Name> 
         <PatternDistancesList>       
              <PatternDistance>278</PatternDistance>
              <PatternDistance>380</PatternDistance>
         </PatternDistancesList> 
     <Pattern/>
     <Pattern> 
          <Name>cat.jpg</Name> 
          <PatternDistancesList>       
              <PatternDistance>278</PatternDistance>
              <PatternDistance>380</PatternDistance>
          </PatternDistancesList> 
     <Pattern/>
</Patterns>

openFileDialog1.FileName returns the full path of the file use openFileDialog1.SafeFileName to get the filename only and you will have your desired result. The strings don't math because one of them gets the file name while the other gets the full path. use openFileDialog1.SafeFileName and i am sure you will get a match.

Try following way using Linq. Answer includes your following query also.

Also, I wanted to know how can I read other corresponding values once I get a match like the different distance values?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string uploadFilename = "dog.jpg";
            XDocument xdoc = XDocument.Load(@"C:\Users\admin\XMLFile1.xml");

            //// check if the xml file is having node mathcing upload filename name 
            List<XElement> xel = xdoc.Descendants("Name").Where(x => x.Value == uploadFilename).ToList();

            if (xel.Any())
            {
                Console.WriteLine("I match the currently open file's name: " + uploadFilename);

                //// Get list of element list's Ancestors
                //// will return
                ////<Name>dog.jpg</Name>
                ////<PatternDistancesList>
                ////  <PatternDistance>278</PatternDistance>
                ////  <PatternDistance>380</PatternDistance>
                ////</PatternDistancesList>

                //// looop through it
                foreach (XElement item in xel.Ancestors("Pattern").Elements().ToList())
                {

                }

                //// OR get another list
                List<XElement> foundItems = xel.Ancestors("Pattern").Elements().ToList();
            }

        }
    }
}

This is basic help using console application. Modify the code accordingly. Hope it helps. :)

Get the filename from file dialog :

string fileName = openFileDialog1.SafeFileName;

Load the XmlDocument:

XDocument xdoc = XDocument.Load(@"C:\Users\Desktop\TangramsTool\patterndata.xml");

Get the matching XElements:

var MatchingPatterns=xdoc.Elements("Pattern").Where(o=>o.Element(Name).Value.Trim()==filename).FirstOrDefault();

if(MatchingPatterns!=null)
{
 Console.WriteLine("I match the currently open file's name: " + fileName );
}

you can get the list of PatternDistance like this:

   List<XElement> patternDistances= MatchingPatterns.Element("PatternDistancesList").Elements("PatternDistance").ToList();

This might Help !

<Patterns>
     <Pattern> 
         <Name>dog.jpg</Name> 
         <PatternDistancesList>       
              <PatternDistance>278</PatternDistance>
              <PatternDistance>380</PatternDistance>
         </PatternDistancesList> 
     </Pattern>
     <Pattern> 
          <Name>cat.jpg</Name> 
          <PatternDistancesList>       
              <PatternDistance>278</PatternDistance>
              <PatternDistance>380</PatternDistance>
          </PatternDistancesList> 
     </Pattern>
</Patterns>

string fileName = openFileDialog1.SafeFileName;

Make sure that filename and node["Name"].InnerText are same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM