如何使用 SchemaVersion 从 XML 进行查询

本文关键字:查询 XML 何使用 SchemaVersion | 更新日期: 2023-09-27 18:33:48

>我有这个XML文件

<?xml version="1.0" encoding="us-ascii" ?> 
<LoanSetupFile SchemaVersion="3.0" NumberOfLoans="2" xmlns="https://www.something.com/schemas">
 <Loan ServicerLoanNumber="1"/>
 <Loan ServicerLoanNumber="2"/>
</LoanSetupFile>

我正在尝试获取 ServicerLoanNumber 属性。我已经尝试了很多方法,这可能是我最接近的尝试,但它仍然返回 null

var doc = XDocument.Load("fileName.xml");
XNamespace ns = doc.Root.GetDefaultNamespace(); //This gives me the correct namespace
var loans = from l in doc.Descendants(ns+"Loan") select new { ServicerLoanNumber = l.Attribute("ServicerLoanNumber").Value };

有谁知道这是怎么回事?我是否需要包含架构版本?如果是这样,如何?

多谢。。

如何使用 SchemaVersion 从 XML 进行查询

我刚刚在 winform 中对您的代码进行了快速测试,它工作正常。

        StringBuilder sb = new StringBuilder();
        sb.Append(@"<?xml version=""1.0"" encoding=""us-ascii"" ?>");
        sb.Append(@"<LoanSetupFile SchemaVersion=""3.0"" NumberOfLoans=""2"" xmlns=""https://www.something.com/schemas"">");
        sb.Append(@"<Loan ServicerLoanNumber=""1""/>");
        sb.Append(@"<Loan ServicerLoanNumber=""2""/>");
        sb.Append(@"</LoanSetupFile>");
        var doc = XDocument.Load(new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString() ?? "")));
        XNamespace ns = doc.Root.GetDefaultNamespace(); //This gives me the correct namespace
        var loans = from l in doc.Descendants(ns + "Loan") 
                    select new { ServicerLoanNumber = l.Attribute("ServicerLoanNumber").Value };
        // Temporarily display the values
        foreach (var l in loans)
        {
            MessageBox.Show(l.ServicerLoanNumber);
        }