C# 从文档中选择单个XML节点
我试图从Philips Hue Bridge返回的XML文档中加载一些值。下面是一个XML示例,我试图解析来自飞利浦网站的示例:C# 从文档中选择单个XML节点,c#,xpath,xml-parsing,C#,Xpath,Xml Parsing,我试图从Philips Hue Bridge返回的XML文档中加载一些值。下面是一个XML示例,我试图解析来自飞利浦网站的示例: <root xmlns="urn:schemas-upnp-org:device-1-0"> <specVersion> <major>1</major> <minor>0</minor> </specVersion> <U
<root xmlns="urn:schemas-upnp-org:device-1-0">
<specVersion>
<major>1</major>
<minor>0</minor>
</specVersion>
<URLBase>https://192.168.1.130:80/</URLBase>
<device>
<deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType>
<friendlyName>Philips hue (192.168.1.130)</friendlyName>
<manufacturer>Royal Philips Electronics</manufacturer><manufacturerURL>https://www.philips.com</manufacturerURL>
<modelDescription>Philips hue Personal Wireless Lighting</modelDescription>
<modelName>Philips hue bridge 2012</modelName>
<modelNumber>929000226503</modelNumber>
<modelURL>https://www.meethue.com</modelURL>
<serialNumber>001788102201</serialNumber>
<UDN>uuid:2f402f80-da50-11e1-9b23-001788102201</UDN>
<presentationURL>index.html</presentationURL>
<iconList>
<icon>
<mimetype>image/png</mimetype>
<height>48</height>
<width>48</width>
<depth>24</depth>
<url>hue_logo_0.png</url>
</icon>
<icon>
<mimetype>image/png</mimetype>
<height>120</height>
<width>120</width>
<depth>24</depth>
<url>hue_logo_3.png</url>
</icon>
</iconList>
</device>
</root>
编辑:
我发现我缺少名称空间。但我不确定如何操作,因为没有指向名称空间的URL。例如
var nsmgr = new XmlNamespaceManager(bridgeDetails.NameTable);
nsmgr.AddNamespace("upnp", "urn:schemas-upnp-org:device-1-0");
XmlNode root = bridgeDetails.DocumentElement;
var friendlyName = bridgeDetails.SelectSingleNode("//upnp:device/friendlyName");
任何帮助都将不胜感激。添加名称空间后,您的解决方案已关闭。 现在使用以下XPath-1.0表达式,因为所有子级或子级都在此命名空间中:
//upnp:device/upnp:friendlyName
总之,这应该是
var friendlyName = bridgeDetails.SelectSingleNode("//upnp:device/upnp:friendlyName", nsmgr);
并将值返回给您
飞利浦色调192.168.1.130
关于你的陈述
但我不确定如何操作,因为没有指向名称空间的URL
命名空间URI不必是有效的URL。它只需是名称空间中唯一的字符串,而不必指向可检索的文件。这不是必需的。您的XML位于根元素上由xmlns=urn:schemas-upnp-org:device-1-0创建的名称空间中。您必须在XPath表达式中尊重这一点,否则它将返回null。因此,请阅读C中的名称空间以及如何在XPath表达式中使用它们。谢谢,我刚刚解决了这个问题,但不知道如何做到这一点。请看我的编辑。谢谢你的工作,虽然我不完全理解为什么在每个元素名称之前需要upnp:。我知道它们都在那个名称空间中,但是当您引用一个您已经指定的子元素时,它就在那个名称空间中,即upnp:device为什么还需要它?名称空间在定义之后由所有子元素继承。如果在其中一个子项上定义了新的默认名称空间,则此名称空间将从此子项继承。
var friendlyName = bridgeDetails.SelectSingleNode("//upnp:device/upnp:friendlyName", nsmgr);