[英]Parsing of XML string (with namespace) using LINQ
My Input 我的意见
<A xmlns="http://abc.com">
<B>"b"</B>
<C>"c"</C>
</A>
My Code 我的守则
XNamespace ns = XNamespace.Get("http://abc.com");
var query= from node in doc.Descendants(ns+ "A")
select new
(
B = (string)node.Element(ns+"B"),
C = (string)node.Element(ns+ "C")
);
My Question 我的问题
Do I have to add ns
every time I am doing node.Element()
? 每次我在做node.Element()
时都要添加ns
吗? or is there any other way? 或者还有其他方法吗?
Do I have to add ns every time I am doing node.Element()? 每次我在做node.Element()时都要添加ns吗?
Yes, basically. 是的,基本上。 You're looking for (say) an element with a local name of B
and a namespace URI of "http://abc.com". 您正在寻找(比方说)具有本地名称B
和名称空间URI“http://abc.com”的元素。
You could write your own extension method which matched any element with the right local name, but I'd advise against it. 您可以编写自己的扩展方法,使用正确的本地名称匹配任何元素,但我建议不要使用它。 It would be something like: 它会是这样的:
public IEnumerable<XElement> ElementsWithLocalName(this XContainer container,
string localName)
{
return container.Elements().Where(x => x.Name.LocalName == localName);
}
public IEnumerable<XElement> ElementsWithLocalName<T>(
this IEnumerable<T> source,
string localName) where T : XContainer
{
return source.Elements().Where(x => x.Name.LocalName == localName);
}
This would make your code less reliable though - do you really want to match just any old name with the right local name? 这会使你的代码不那么可靠 - 你真的想要将任何旧名称与正确的本地名称匹配吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.