简体   繁体   English

如何读取特定的XML节点?

[英]How to read a specific XML node?

I have an XML file with data corresponding to multiple objects. 我有一个XML文件,其中的数据对应于多个对象。 I am trying to open the XML file, loop through to find a specific filename and read in all the values associated with that. 我正在尝试打开XML文件,循环查找特定的文件名并读取与此相关的所有值。

Problem: 问题:

It never has a match between an XMLElement's Name and the file name. XMLElement的名称和文件名之间永远不会匹配。 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". 我想发生的事情:因此,当用户在OpenFileDialog中打开“ dog.jpg”时,XML文档就会被加载,并且应该能够找到值为dog.jpg的XML元素“ 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 : 我的Open方法中的代码:

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: 我的XML文件:

<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. openFileDialog1.FileName返回文件的完整路径,使用openFileDialog1.SafeFileName仅获取文件名,您将获得所需的结果。 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. 使用openFileDialog1.SafeFileName,我相信你会得到一个匹配。

Try following way using Linq. 尝试使用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: 加载XmlDocument:

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

Get the matching XElements: 获取匹配的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: 您可以像这样获得PatternDistance的列表:

   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 确保文件名和节点[“名称”] .InnerText相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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