简体   繁体   English

从 XML 文件中读取属性

[英]Reading attribute from an XML file

I have an XML file which looks like this我有一个看起来像这样的 XML 文件

<SendInvoiceResult xmlns="http://tempuri.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IsSucceded="true">
  <Value Id="123456" Number="1" InvoiceScenario="Scenario" /> 
</SendInvoiceResult>

I'm trying to read the attributes of this file but so far all my tries based on other questions on Stackoverflow either returned null or "Object reference not set to an instance of an object" error.我正在尝试读取此文件的属性,但到目前为止,我所有的尝试都基于 Stackoverflow 上的其他问题,要么返回 null 要么“对象引用未设置为对象的实例”错误。

My latest try is this:我最近的尝试是这样的:

var testXml = new XmlDocument();
testXml.LoadXml(test);

var node = testXml.SelectSingleNode("/SendInvoiceResult/Value");
var id = node.Attributes["Id"].Value;

This approach returns "Object reference not set to an instance of an object" too.这种方法也返回“对象引用未设置为对象的实例”。 I'm wondering if something is wrong with the way XML is structures at this point.我想知道此时 XML 的结构方式是否有问题。

I'm open to new methods and suggestions of course, all I need is to read the values of attributes in this and other similar XML files.当然,我对新方法和建议持开放态度,我只需要读取此文件和其他类似 XML 文件中的属性值。

Use XDocument.使用 XDocument。 It is much more modern and capable.它更加现代和强大。

var doc = XElement.Load(test);
var id = doc.Root.Element("Value").Attribute("Id").Value;

You must define xml namespace.您必须定义 xml 命名空间。

var doc = new XmlDocument();
doc.Load("test.txt");

var manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("ns", "http://tempuri.org/");

var node = doc.SelectSingleNode("/ns:SendInvoiceResult/ns:Value", manager);
var id = node.Attributes["Id"].Value;

Console.WriteLine(id);

Better use modern and more convenient linq to xml.更好地使用现代更方便的 linq 到 xml。

using System.Xml.Linq;

var doc = XDocument.Load("test.txt");
XNamespace ns = "http://tempuri.org/";
var id = doc.Root.Element(ns + "Value").Attribute("Id").Value;
Console.WriteLine(id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM