简体   繁体   中英

C# Error when reading Xml Attribute

I'm developing my first WPF application with C# but I have a problem when I'm trying to read a Xml attribute.

I have the following 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>`

Now I try to get the Attribute "Content" with the following method:

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

But it doesn't work:

Error : ex {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}

I have tried using 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;

Inorder to use this you have to include System.Xml.Linq namespace

You got

null reference exception

because you didn't check for null in case your IDAttribute doesn't exist in the XML .

Just change to your path and it will work.

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

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