我有这样的代码:
/*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);
}
当我对theXml使用第一个值时,结果是null,而对于第二个值,我有很好的值……
如何使用带有xmlns值的Linq to Xml?
发布于 2010-02-26 17:06:27
您可以将带有命名空间的XName传递给Descendants()和Element()。当您将字符串传递给Descendants()时,它会隐式转换为不带名称空间的XName。
要在名称空间中创建名称,需要创建一个XNamespace并将其连接到元素local- XName (一个字符串)。
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"),
};
还有一种简写形式,可以通过从字符串进行隐式转换来创建具有名称空间的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"),
};
或者,您可以针对XElement.Name.LocalName进行查询。
var elements = from data in xmlElements.Descendants()
where data.Name.LocalName == "Result"
发布于 2017-04-13 07:56:54
我在XML文档的顶部列出了几个名称空间,我并不真正关心哪些元素来自哪个名称空间。我只想通过它们的名称来获取元素。我已经编写了这个扩展方法。
/// <summary>
/// A list of XElement descendent elements with the supplied local name (ignoring any namespace), or null if the element is not found.
/// </summary>
public static IEnumerable<XElement> FindDescendants(this XElement likeThis, string elementName) {
var result = likeThis.Descendants().Where(ele=>ele.Name.LocalName==elementName);
return result;
}
发布于 2016-04-05 01:40:29
我发现下面的代码可以很好地在VB.NET中读取带有名称空间的属性:
MyXElement.Attribute(MyXElement.GetNamespaceOfPrefix("YOUR_NAMESPACE_HERE") + "YOUR_ATTRIB_NAME")
希望这对以后的人有所帮助。
https://stackoverflow.com/questions/2340411
复制相似问题