如何使用SchemaVersion从XML查询?

时间:2014-12-09 20:39:03

标签: c# xml linq

我有这个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吗?如果是这样,怎么样?

非常感谢..

1 个答案:

答案 0 :(得分:0)

我刚刚在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);
        }