Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ解析XML字符串(带命名空间)_C#_Visual Studio 2010_Linq_Xml Parsing - Fatal编程技术网

C# 使用LINQ解析XML字符串(带命名空间)

C# 使用LINQ解析XML字符串(带命名空间),c#,visual-studio-2010,linq,xml-parsing,C#,Visual Studio 2010,Linq,Xml Parsing,我的输入 <A xmlns="http://abc.com"> <B>"b"</B> <C>"c"</C> </A> 我的问题 每次执行node.Element(),是否都必须添加ns?或者还有别的办法吗 是否每次执行node.Element()时都必须添加ns 是的,基本上。您正在寻找(比如)一个本地名为B且名称空间URI为的元素http://abc.com“ 您可以编写自己的扩展方法来匹配任何

我的输入

<A xmlns="http://abc.com"> 
    <B>"b"</B>
    <C>"c"</C>
    </A>
我的问题

每次执行
node.Element()
,是否都必须添加
ns
?或者还有别的办法吗

是否每次执行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);
}
公共IEnumerable元素SwithLocalName(此XContainer容器,
字符串(本地名称)
{
返回container.Elements(),其中(x=>x.Name.LocalName==LocalName);
}
公共IEnumerable元素的本地名称(
这是一个数不清的来源,
字符串localName),其中T:XContainer
{
返回source.Elements(),其中(x=>x.Name.LocalName==LocalName);
}

但是,这会降低代码的可靠性-您真的想将任何旧名称与正确的本地名称进行匹配吗?

这里也有一个相关的问题:我相信
XPath
可以提供另一种选择,但它比您在这里所做的更复杂。不,我真的不想这样做,但我认为doc.subjections(ns+“a”)有道理,但对于子节点来说,这不是冗余信息吗?这是否意味着A下的任何节点都将具有与A的命名空间URI相同的命名空间URI?
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);
}