c# – 使用LINQ解析XML字符串(带名称空间)
发布时间:2020-12-15 04:35:49 所属栏目:百科 来源:网络整理
导读:我的意见 A xmlns="http://abc.com" B"b"/B C"c"/C /A 我的守则 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") )
我的意见
<A xmlns="http://abc.com"> <B>"b"</B> <C>"c"</C> </A> 我的守则 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") ); 我的问题 每次我在做node.Element()时都要添加ns吗?或者还有其他方法吗? 解决方法
是的,基本上.您正在寻找(比方说)具有本地名称B和名称空间URI“http://abc.com”的元素. 您可以编写自己的扩展方法,使用正确的本地名称匹配任何元素,但我建议不要这样做.它会是这样的: 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); } 这会使你的代码不那么可靠 – 你真的想要将任何旧名称与正确的本地名称匹配吗? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |