Tim*_*Tim 56 c# linq-to-xml xml-namespaces
我有这个代码:
/*string theXml =
@"<Response xmlns=""http://myvalue.com""><Result xmlns:a=""http://schemas.datacontract.org/2004/07/My.Namespace"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><a:TheBool>true</a:TheBool><a:TheId>1</a:TheId></Result></Response>";*/
string theXml = @"<Response><Result><TheBool>true</TheBool><TheId>1</TheId></Result></Response>";
XDocument xmlElements = XDocument.Parse(theXml);
var elements = from data in xmlElements.Descendants("Result")
select new {
TheBool = (bool)data.Element("TheBool"),
TheId = (int)data.Element("TheId"),
};
foreach (var element in elements)
{
Console.WriteLine(element.TheBool);
Console.WriteLine(element.TheId);
}
Run Code Online (Sandbox Code Playgroud)
当我使用第一个值为xml时,结果为null,而对于第二个值,我有很好的值...
如何使用xmlns值将Linq用于Xml?
Mik*_*Two 88
LINQ to XML方法喜欢Descendants并将Element其XName作为参数.有一个从转换string到XName时自动发生的事情给你.您可以通过XNamespace在Descendants和Element调用中添加字符串来解决此问题.请注意,因为您有两个不同的命名空间.
string theXml =
@"true1";
//string theXml = @"true1";
XDocument xmlElements = XDocument.Parse( theXml );
XNamespace ns = "http://myvalue.com";
XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";
var elements = from data in xmlElements.Descendants( ns + "Result" )
select new
{
TheBool = (bool) data.Element( nsa + "TheBool" ),
TheId = (int) data.Element( nsa + "TheId" ),
};
foreach ( var element in elements )
{
Console.WriteLine( element.TheBool );
Console.WriteLine( element.TheId );
}
注意使用ns in Descendants和nsaElements
Lac*_*che 26
您可以将带有命名空间的XName传递给Descendants()和Element().将字符串传递给Descendants()时,它会隐式转换为没有名称空间的XName.
要在命名空间中创建XName,请创建XNamespace并将其连接到元素local-name(字符串).
XNamespace ns = "http://myvalue.com";
XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";
var elements = from data in xmlElements.Descendants( ns + "Result")
select new
{
TheBool = (bool)data.Element( nsa + "TheBool"),
TheId = (int)data.Element( nsa + "TheId"),
};
Run Code Online (Sandbox Code Playgroud)
还有一种简写形式,用于通过从字符串的隐式转换来创建具有命名空间的XName.
var elements = from data in xmlElements.Descendants("{http://myvalue.com}Result")
select new
{
TheBool = (bool)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheBool"),
TheId = (int)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheId"),
};
Run Code Online (Sandbox Code Playgroud)
或者,您可以查询XElement.Name.LocalName.
var elements = from data in xmlElements.Descendants()
where data.Name.LocalName == "Result"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45571 次 |
| 最近记录: |