简体   繁体   中英

How to query from XML with SchemaVersion?

I have this XML file

<?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. I've tried a lot of ways, and this might be my closest attempt, but still it's returning 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? If so, how?

Thanks a lot..

I just did a quick test of your code in a winform, it is working fine.

        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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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