简体   繁体   中英

Parsing XML file C#

I can't parse the attribute value from this file, I used Linq and the standard library. Object reference error. Need attribut's value "RequeryNumber".

在此处输入图像描述

XML file

Excel Query:

exctract = XML.DocumentElement
    .SelectSingleNode("//KPOKS/ReestrExtract/DeclarAttribute")
    .Attributes
    .getNamedItem("RequeryNumber").Text

SelectSingleNode() uses XPath to find XML nodes that fulfill the filter. There are several ways to get what you want. If RequeryNumber only exists on one node, you could do like this:

var attribute = xDoc.DocumentElement
    .SelectSingleNode("//*[@RequeryNumber]/@RequeryNumber");

MessageBox.Show("text" + attribute.InnerText);

[@RequeryNumber] finds the node which has an attribute named "RequeryNumber".

/@RequeryNumber extracts that specific attribute, on which you can get the value using the InnerText property.

I would suggest you take a look at: XPath cheatsheet

I had one error on following line in the xml that I fixed

I parsed below your xml and needed to add the namespace to get the XElement using Xml Linq.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetDefaultNamespace();

            XElement declarAttribute = doc.Descendants(ns + "DeclarAttribute").FirstOrDefault();
        }
    }
}

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