我有一个带有属性的XML文件
xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
删除此属性时,我可以读取每个标签。如果我不删除属性,我会收到错误消息"对象未设置对象的实例"
我的C#代码:
XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/HotelSearchCriteria/PrepareBooking.xml"));
string CommmitLevel = xml.DocumentElement
.SelectSingleNode("/BookingCreate/CommitLevel")
.InnerText;
我的XML:
<BookingCreate xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
<Authority>
<Org>danco</Org>
<User>xmltest</User>
<Password>xmltest</Password>
<Language>en</Language>
<Currency>EUR</Currency>
<TestDebug>false</TestDebug>
<Version>1.26</Version>
</Authority>
<QuoteId>17081233-3</QuoteId>
<HotelStayDetails>
<Room>
<Guests>
<Adult title="Mr" first="djkvb" last="jkj" />
<Adult title="Mr" first="jfs" last="kjdjs" />
</Guests>
</Room>
</HotelStayDetails>
<HotelSearchCriteria>
<AvailabilityStatus>allocation</AvailabilityStatus>
<DetailLevel>basic</DetailLevel>
</HotelSearchCriteria>
<CommitLevel>prepare</CommitLevel>
</BookingCreate>
如何使用XMLNS属性读取XML?我有必要拥有XMLNS属性。
您需要使用名称空间管理器指定命名空间。这应该有效
XmlDocument bookingXml = new XmlDocument();
bookingXml.Load("PrepareBooking.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(bookingXml.NameTable);
ns.AddNamespace("booking", "http://www.reservwire.com/namespace/WebServices/Xml");
var commitLevel = bookingXml.SelectSingleNode("//booking:BookingCreate//booking:CommitLevel", ns).InnerText;
使用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:temptest.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement bookingCreate = doc.Descendants().Where(x => x.Name.LocalName == "BookingCreate").FirstOrDefault();
XNamespace ns = bookingCreate.GetDefaultNamespace();
var results = doc.Descendants(ns + "BookingCreate").Select(x => new {
org = (string)x.Descendants(ns + "Org").FirstOrDefault(),
user = (string)x.Descendants(ns + "User").FirstOrDefault(),
password = (string)x.Descendants(ns + "Password").FirstOrDefault(),
language = (string)x.Descendants(ns + "Language").FirstOrDefault(),
currency = (string)x.Descendants(ns + "Currency").FirstOrDefault(),
testDebug = (Boolean)x.Descendants(ns + "TestDebug").FirstOrDefault(),
version = (string)x.Descendants(ns + "Version").FirstOrDefault(),
quoteId = (string)x.Element(ns + "QuoteId"),
guests = x.Descendants(ns + "Adult").Select(y => new {
title = (string)y.Attribute("title"),
first = (string)y.Attribute("first"),
last = (string)y.Attribute("last")
}).ToList(),
availability = (string)x.Descendants(ns + "AvailabilityStatus").FirstOrDefault(),
detailLevel = (string)x.Descendants(ns + "DetailLevel").FirstOrDefault()
}).FirstOrDefault();
}
}
}