简体   繁体   English

如何使用SchemaVersion从XML查询?

[英]How to query from XML with SchemaVersion?

I have this XML file 我有这个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>

I'm trying to get the ServicerLoanNumber attribute. 我正在尝试获取ServicerLoanNumber属性。 I've tried a lot of ways, and this might be my closest attempt, but still it's returning null 我已经尝试了很多方法,这可能是我最接近的尝试,但是仍然返回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 };

Does anyone know what's wrong with this? 有谁知道这是怎么回事? Do I need to include the SchemaVersion? 我是否需要包含SchemaVersion? If so, how? 如果是这样,怎么办?

Thanks a lot.. 非常感谢..

I just did a quick test of your code in a winform, it is working fine. 我只是在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);
        }

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

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