读取Xml属性时出现C#错误

时间:2016-06-28 13:45:20

标签: c# xml

我正在使用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>`

现在我尝试使用以下方法获取属性“内容”:

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 {“对象引用未设置为对象的实例。”} System.Exception {System.NullReferenceException}

2 个答案:

答案 0 :(得分:1)

我尝试过使用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命名空间

答案 1 :(得分:1)

你有

  

null引用异常

因为如果 XML 中不存在 IDAttribute ,则您未检查 null

只需改变你的路径即可。

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;
        }
相关问题