C# 解析XML无效
我试图将这个xml文件解析为一个对象,以使用它收集的信息。我附上一个xml示例。XDocument填充了xml信息,但它无法获得我想要的信息。有人能帮帮我吗,我是新手 编辑-仅仅因为你没有看到我正在寻找的字段并不意味着它不存在。我仔细检查了所有的值,它们确实存在,Bill对象非常大,所以我只放了一部分 示例xmlC# 解析XML无效,c#,asp.net,xml,C#,Asp.net,Xml,我试图将这个xml文件解析为一个对象,以使用它收集的信息。我附上一个xml示例。XDocument填充了xml信息,但它无法获得我想要的信息。有人能帮帮我吗,我是新手 编辑-仅仅因为你没有看到我正在寻找的字段并不意味着它不存在。我仔细检查了所有的值,它们确实存在,Bill对象非常大,所以我只放了一部分 示例xml <results> <count type="integer">13683</count> <bills type="array"&g
<results>
<count type="integer">13683</count>
<bills type="array">
<bill>
<abbreviated type="boolean">false</abbreviated>
<actions type="array">
<action>
<type>vote</type>
<acted_at type="datetime">2010-12-22T12:00:00Z</acted_at>
<text>Introduced in the Senate, read twice, considered, read the third time, and passed without amendment by Unanimous Consent.</text>
</action>
<action>
<type>action</type>
<acted_at type="datetime">2010-12-22T12:00:00Z</acted_at>
<text>Message on Senate action sent to the House.</text>
</action>
<action>
<type>action</type>
<acted_at type="datetime">2010-12-22T21:05:00Z</acted_at>
<text>Received in the House.</text>
</action>
<action>
<type>action</type>
<acted_at type="datetime">2010-12-22T22:10:00Z</acted_at>
<text>Held at the desk.</text>
</action>
</actions>
<awaiting_signature type="boolean">false</awaiting_signature>
<bill_id>s4053-111</bill_id>
<bill_type>s</bill_type>
<chamber>senate</chamber>
<code>s4053</code>
<committees></committees>
<cosponsor_ids type="array">
<cosponsor_id>S000663</cosponsor_id>
</cosponsor_ids>
我的代码(我已经尝试将“bill”和“bills”作为后代。)
Xml中既没有
赞助者id
也没有赞助者
或名字
元素(依此类推),因此基本上您的Xml与代码所期望的完全不同-无论“bill”和“bills”如何,这都无法工作。这是错误的Xml文件。检查其他文件。不是真的,我仔细检查了所有值,它们确实存在,Bill对象非常大,所以我只在这里放了一部分。即使这些元素不存在,它也应该撤回一个bill元素,而它甚至不这样做。不,它将在选择新..
中抛出一个异常-您必须确保所有需要的元素都在那里。在初始查询中,它看起来应该是bill
。在内的第一行设置一个断点,然后选择new
并从那里开始。在您的右边,我将其缩减为仅一个字段进行测试,然后返回结果。我猜其中一些字段是可选的,可能不会显示,因此我必须检查账单中是否存在这些字段。如果该字段不存在,如何返回空字符串?有什么建议吗?是-而不是例如SponsorID=tutorial.Element(“赞助商id”).Value
useSponsorID=(string)tutorial.Element(“赞助商id”)
-这样,如果元素不存在,属性将被设置为null
。
var tutorials = from tutorial in xmlDoc.Descendants("bills")
select new
{
SponsorID = tutorial.Element("sponsor_id").Value,
SponsorFirstName = tutorial.Element("sponsor").Element("first_name").Value,
SponsorLastName = tutorial.Element("sponsor").Element("last_name").Value,
LastActionText = tutorial.Element("last_action").Element("text").Value,
BillNumber = tutorial.Element("number").Value,
BillType = tutorial.Element("bill_type").Value,
Enacted = tutorial.Element("enacted").Value,
EnactedDateTime = tutorial.Element("enacted_at").Value,
CongressSession = tutorial.Element("session").Value,
HousePassageResult = tutorial.Element("house_passage_result").Value,
HousePassageDateTime = tutorial.Element("house_passage_result_at").Value,
SenatePassageResult = tutorial.Element("senate_passage_result").Value,
SenatePassageDateTime = tutorial.Element("senate_passage_result_at").Value,
ShortTitle = tutorial.Element("short_title").Value,
};