我正在尝试获取的值Address
以下 XML 文本中的元素,但除非我删除,否则找不到它xmlns="http://www.foo.com"
来自Root
元素。然而,即使使用它,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(xmlTextAbove);
var address = doc.Descendants().Where(o => o.Name == "Address").FirstOrDefault();
Console.WriteLine(address.Value); // <-- error, address is null.
由于您的 xml 包含名称空间,因此您必须在代码中提及它。这将起作用:
XNamespace nsSys = "http://www.foo.com";
XElement xDoc = XElement.Load("1.xml");
XElement xEl2 = xDoc.Descendants(nsSys + "Address").FirstOrDefault();
但是我不得不稍微改变你的 xml,因为它包含重复的内容xmlns:xsi
and 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>
MSDN 中的相关文章:X命名空间类
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)