【问题标题】:How to read a specific XML node?如何读取特定的 XML 节点?
【发布时间】:2015-12-18 22:21:24
【问题描述】:

我有一个 XML 文件,其中的数据对应于多个对象。我正在尝试打开 XML 文件,循环查找特定文件名并读取与之相关的所有值。

问题:

XMLElement 的名称和文件名之间永远不会匹配。所以“我匹配当前打开的文件名”永远不会被打印出来。

我想要发生的事情: 因此,当用户在 OpenFileDialog 中打开“dog.jpg”时,XML 文档会被加载,它应该能够找到 XML 元素“名称”与值 dog.jpg 并打印“我匹配当前打开的文件的名称”。

另外,我想知道如何在获得不同距离值等匹配后读取其他对应值?

我的 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);
         }
    }

我的 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>

【问题讨论】:

  • 你在节点列表中得到了什么?
  • 我得到一个不同 节点的列表,然后我为每个节点读取“名称”。
  • 尝试在linq中寻找答案。
  • XML 区分大小写,你确定你有 dog.jpg 作为文件名吗?
  • 啊,愚蠢的错误>.

标签: c# xml wpf


【解决方案1】:

使用 Linq 尝试以下方式。答案还包括您的以下查询。

另外,我想知道,一旦我得到一个匹配的值,比如不同的距离值,我该如何读取其他对应的值?

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();
            }

        }
    }
}

这是使用控制台应用程序的基本帮助。相应地修改代码。希望能帮助到你。 :)

【讨论】:

  • 谢谢你,我现在正在尝试实现它,我只是想知道如何只将距离值添加到新列表中(忽略名称和距离列表)?
  • 我了解到您想要距离列表值 278 和 380 数学名称值。 //// Result ill have list of string having value 278 and 380 List&lt;string&gt; distanceValues = new List&lt;string&gt;(); foreach (XElement item in xel.Ancestors("Pattern").Descendants("PatternDistance")) { distanceValues.Add(item.Value); }
  • 非常感谢!它有效:D 我认为我需要花时间阅读关于祖先和后代的整个树结构,以正确理解它。
  • 欢迎朋友。很高兴它有帮助。 :)
【解决方案2】:

openFileDialog1.FileName 返回文件的完整路径 使用 openFileDialog1.SafeFileName 仅获取文件名,您将获得所需的结果。字符串不进行数学运算,因为其中一个获取文件名,而另一个获取完整路径。使用 openFileDialog1.SafeFileName 我相信你会得到一个匹配。

【讨论】:

  • 你是对的!这正是我遇到的问题。谢谢你:)
【解决方案3】:

从文件对话框中获取文件名:

string fileName = openFileDialog1.SafeFileName;

加载 XmlDocument:

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

获取匹配的 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 );
}

你可以像这样得到 PatternDistance 的列表:

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

这可能会有所帮助!

【讨论】:

  • 当我尝试实现代码的最后一位以将值存储到列表中时,它给出了一条错误消息:错误 2 无法隐式转换类型 'System.Collections.Generic.IEnumerable' 到 'bool'
  • 没有布尔值。上述解决方案对我来说很好。
  • 抱歉,我没有看到您更新的答案。使用完全相同的代码,在最后一行,现在它给出了这个错误,不能隐式地将类型 'System.Collections.Generic.IEnumerable' 转换为 'System.Collections.Generic.List'。存在显式转换(您是否缺少演员表?)
  • 将 ToList() 添加到最后一行。
  • 哦,这就是我在使用列表时没有说清楚的。它现在可以工作了:D 非常感谢您的帮助。
【解决方案4】:
<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;

确保文件名和节点["Name"].InnerText 相同

【讨论】:

  • @Nikita- 文件名返回完整路径,SafeFileName 返回文件名和扩展名
猜你喜欢
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
  • 1970-01-01
相关资源
最近更新 更多