Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.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# 为什么XDocument可以';是否无法从该wellform XML文本中获取元素?_C#_Xml_Linq To Xml - Fatal编程技术网

C# 为什么XDocument可以';是否无法从该wellform XML文本中获取元素?

C# 为什么XDocument可以';是否无法从该wellform XML文本中获取元素?,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我试图从下面的XML文本中获取Address元素的值,但除非我删除xmlns=,否则它找不到它http://www.foo.com“来自根元素。但是,即使使用XML,它也是有效的。这里有什么问题 因为我是从web服务获取XML文本的,所以我无法控制它,但是如果必须的话,我可以去掉xmlns部分作为最后手段 <?xml version="1.0" encoding="utf-8"?> <Root xmlns:xsi="http://www.w3.org/2001/XMLSchem

我试图从下面的XML文本中获取
Address
元素的值,但除非我删除
xmlns=,否则它找不到它http://www.foo.com“
来自
根元素。但是,即使使用XML,它也是有效的。这里有什么问题

因为我是从web服务获取XML文本的,所以我无法控制它,但是如果必须的话,我可以去掉
xmlns
部分作为最后手段

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
      xmlns="http://www.foo.com">
  <Address>Main St SW</Address>
</Root>

主街西南
var doc=XDocument.Parse(XMLTextUpper);
var address=doc.subjects()。其中(o=>o.Name==“address”).FirstOrDefault();

Console.WriteLine(address.Value);// 由于xml包含名称空间,因此必须在代码中提到这一点。这将有助于:

    XNamespace nsSys = "http://www.foo.com";
    XElement xDoc = XElement.Load("1.xml");
    XElement xEl2 = xDoc.Descendants(nsSys + "Address").FirstOrDefault();
但是,我必须稍微更改一下您的xml,因为它包含重复的
xmlns:xsi
xmlns:xsd
,每个xml格式只能出现一次:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns="http://www.foo.com" >
  <Address>Main St SW</Address>
</Root>


文档根的XML名称空间包含在
o.Name
的文本表示中,它实际上是的一个实例,因此条件永远不匹配

最简单的修复方法是用于比较:

.Where(o => o.Name.LocalName == "Address")

+我也不知道这件事,因为我从昨天起就一直在做这件事。谢谢:)
.Where(o => o.Name.LocalName == "Address")