c#读取Xml属性时出错

本文关键字:出错 属性 Xml 读取 | 更新日期: 2023-09-27 17:52:55

我正在用c#开发我的第一个WPF应用程序,但是当我试图读取Xml属性时,我遇到了一个问题。

我有以下Xml:

<?xml version="1.0" encoding="utf-8"?>
<Dictionary EnglishName="Italian" CultureName="Italian" Culture="">
    <!-- MainWindow -->
    <Value ID="WpfApplication1.MainWindow.BtnDrawCircle" Content="Circonferenza"/>
    <Value ID="WpfApplication1.MainWindow.BtnDrawLine" Content="Linea"/>
    ....
    ....
</Dictionary>`

现在我尝试用以下方法获得属性"Content":

public static string ReadNodeAttribute(string IDAttribute)
    {
        try
        {
            XmlDocument _Doc = new XmlDocument();
            _Doc.Load("myPath''Language''it-IT.xml");
            string _Value = _Doc.SelectSingleNode("//Value[@ID=" + IDAttribute + "]").Attributes["Content"].Value.ToString();
            return _Value;
        }
        catch (Exception ex)
        {
            return null;
        }
}

但是它不工作:

错误:ex{"对象引用未设置为对象的实例。"}系统。异常{系统。得到NullReferenceException}

c#读取Xml属性时出错

null引用异常

因为你没有检查null,以防IDAttributeXML中不存在。

只要改变你的路径,它就会工作。

using System;
using System.Linq;
using System.Xml.Linq;
  public static string ReadNodeAttribute(string IDAttribute)
        {
            string _Value = "";
            try
            {
               //I used System.IO.Path.GetFullPath because I tried it with ConsoleApplication.
               //Use what ever work for you to load the xml.
                XDocument xdoc = XDocument.Load(System.IO.Path.GetFullPath("XMLFile1.xml"));
                var myValue = xdoc.Descendants("Value").FirstOrDefault(i => i.Attribute("ID").Value == IDAttribute);
                if (myValue != null)
                {
                    _Value = myValue.Attribute("Content").Value;
                    return _Value;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return _Value;
        }

我试过使用Linq to Xml

 XDocument xdoc = XDocument.Load(Server.MapPath("path"));
 var val = xdoc.Descendants("Value").Where(i => i.Attribute("ID").Value == IDAttribute).FirstOrDefault().Attribute("Content").Value;

为了使用这个,你必须包含System.Xml.Linq命名空间