无法使用foreach获取XML值

时间:2017-11-20 00:37:45

标签: c# xml nullreferenceexception

我想使用foreach获取subdata和subdata2值,但由于某种原因,我得到一个空引用异常。

XML:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using TaskApplication.Models;

namespace TaskApplication
{
    // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<IdentityDbContext>()));
            //var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(new IdentityDbContext("DefaultConnection")));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = 
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    // Configure the application sign-in manager which is used in this application.
    public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }
}

代码:

<project>
<name>Name1</name>
<data>
    <subdata>1</subdata>
    <subdata2>1</subdata2>
</data>
<data>
    <subdata>3</subdata>
    <subdata2>2</subdata2>
</data>
</project>

例外:

  

System.NullReferenceException:'对象引用未设置为   对象的实例。 innerDataNode为null。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

您不是在节点的当前上下文中搜索。差异只是一个点。所以

innerDataNode = datanode.SelectSingleNode("/subdata");

应该是:

innerDataNode = datanode.SelectSingleNode("./subdata");

这是一个小错误,发生在我们很多人身上。但这似乎不是你唯一的错误:

XmlNode datanode = doc.DocumentElement.SelectSingleNode("/project/data");

只为您提供一个datanode,并根据您希望所有数据节点的其余代码进行判断。所以你必须这样做:

XmlNodeList datanodes = doc.DocumentElement.SelectNodes("/project/data");

现在你的foreach循环是正确的,但你继续选择datanode而不是你想要循环的变量(dataVar)。

XmlNode innerDataNode;
foreach (XmlNode dataVar in datanodes)
{
    innerDataNode = dataVar.SelectSingleNode("./subdata");
    Console.WriteLine(innerDataNode.InnerText);
}