我有一个这样的XML文档:
<?xml version="1.0" encoding="utf-8"?>
<Settings updated="3/21/2017 15:48">
<Setting name="ToolTipVariables"><?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Title</string>
<string>Date</string>
<string>Description</string>
<string>Location</string>
<string>Id</string>
</ArrayOfString></Setting>
<Setting name="ToolTipVariables"><?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Title</string>
<string>Date</string>
<string>Description</string>
<string>Location</string>
<string>Id</string>
</ArrayOfString></Setting>
<Setting name="ToolTipVariables"><?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Title</string>
<string>Date</string>
<string>Description</string>
<string>Location</string>
<string>Id</string>
</ArrayOfString></Setting>
<Setting name="ShowUpdateWindow"><?xml version="1.0" encoding="utf-16"?>
<boolean>true</boolean></Setting>
</Settings>
我正试图抓住第一个&#34; ToolTipVariables&#34;像这样的元素:
XDocument document = XDocument.Load(settingsPath); //settingsPath is where the XML Document is located
XElement element = document.Descendants("Settings").Where(x => x.Attribute("name").Value == "ToolTipVariables").FirstOrDefault();
但它在尝试获取FirstOrDefault时不断抛出空引用异常。也许我在某个地方犯了一个简单的错误,但我无法找到它。任何帮助将不胜感激!
答案 0 :(得分:1)
问题是您正在选择名为Settings
的所有元素(其中实际上是根节点。)代码document.Descendants("Settings")
将为您提供文档的所有后代,其中元素名称为{{ 1}}。我认为你真正想要的是所有Settings
元素。这将有效:
Setting