gpt4 book ai didi

c# - 空引用异常 - 使用 Element 和 XPath 的 XDocument

转载 作者:行者123 更新时间:2023-12-02 02:29:33 27 4
gpt4 key购买 nike

我正在从数据库中获取一些字符串形式的 XML 数据。数据以ntext形式保存在数据库中。

从数据库获取数据不是问题。问题是稍后,当我想处理xml中的数据时。我将字符串加载到 xDocument 中。

我想首先获取 Owner 值。但是我得到了一个空引用异常,这意味着我没有编写我假设的正确的 Xpath。

写“./Owner”不起作用。写“/./Owner”不起作用,然后我得到一个 XML 异常。

我开始使用 XMLDocument,但我认为遇到了命名空间问题。开始阅读,看起来使用 xDocument 更好。正如您还可以通过我的代码看到的,我尝试通过两种方式获取 Owner 值,但都失败了。

我的 XML 看起来有点像这样:

    <Container xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="DM">
<IsConsigned>false</IsConsigned>
<LockState>Unlocked</LockState>
<SourceType i:nil="true" />
<Id>04216194-4f62-47ee-ab21-c1053d01bf1e</Id>
<Owner>IN</Owner>
<Created>2012-08-21T09:29:10.528321+02:00</Created>
</Container>

我的代码:

      class Program
{
static SqlConnection conn = new SqlConnection();
static XDocument xml = new XDocument();

static void Main(string[] args)
{
using (conn)
{
conn.ConnectionString = Properties.Settings.Default.connectionString;
//connection.Open();
conn.Open();
SqlDataReader reader = GetDataFromDatabase();

if (reader.HasRows)
{

while (reader.Read())
{
string xmlFile = reader.GetSqlString(0).ToString();
HandleData(xmlFile);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}

public static void HandleData(string xmlIn)
{

xml = XDocument.Parse(xmlIn);
XElement xmlElement = xml.Root;
string test1 = xml.Element("Owner").Value.ToString();
string test = xmlElement.Element("Owner").Value.ToString();
}

}

最佳答案

这不是使用 XmlDocument 的问题或XDocument 。您的 XML 有默认命名空间,这是一个没有前缀声明的命名空间,在这里:

xmlns="DM"

与前缀 i 的对比这里:xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 。请注意,不仅声明默认命名空间的元素位于该命名空间中,而且所有后代元素都隐式继承祖先默认命名空间,除非另有指定(使用指向不同命名空间 uri 的显式命名空间前缀或本地默认命名空间)。

您可以使用 "XNamespace"+"element's local name" 的组合形成一个限定名称来引用命名空间中的元素,例如:

var xmlIn = @"<Container xmlns:i='http://www.w3.org/2001/XMLSchema-instance' xmlns='DM'>
<IsConsigned>false</IsConsigned>
<LockState>Unlocked</LockState>
<SourceType i:nil='true' />
<Id>04216194-4f62-47ee-ab21-c1053d01bf1e</Id>
<Owner>IN</Owner>
<Created>2012-08-21T09:29:10.528321+02:00</Created>
</Container>";
var xml = XDocument.Parse(xmlIn);
XNamespace d = "DM";
string owner = xml.Root.Element(d+"Owner").Value;
Console.WriteLine(owner);
string id = xml.Root.Element(d+"Id").Value;
Console.WriteLine(id);

Dotnetfiddle Demo

输出:

IN
04216194-4f62-47ee-ab21-c1053d01bf1e

旁注:

关于c# - 空引用异常 - 使用 Element 和 XPath 的 XDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31532419/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com