【发布时间】:2014-06-08 09:36:40
【问题描述】:
我知道这是一个关于 SO 的重复问题,但我这些答案并没有真正帮助。我正在尝试使用带有 C# 的 Classify API 来获取一本书的详细信息。它给出了XML 输出,例如:
<classify xmlns="http://classify.oclc.org">
<response code="2"/>
<!--
Classify is a product of OCLC Online Computer Library Center: http://classify.oclc.org
-->
<work author="Coelho, Paulo | Clarke, Alan [Author; Translator] | Sampere, Daniel, 1985- [Illustrator; Draftsman] | Lemmens, Harrie, 1953- [Translator] | Smith, James Noel | Ruiz, Derek, 1980- [Adapter]" editions="176" format="Book" holdings="7530" itemtype="itemtype-book" pswid="1151562357" title="The alchemist">123115868</work>
<authors>
<author lc="n94113544" viaf="65709090">Clarke, Alan [Author; Translator]</author>
<author lc="no2005013941" viaf="12032914">Lemmens, Harrie, 1953- [Translator]</author>
<author lc="no2010190009" viaf="160023476">Sampere, Daniel, 1985- [Illustrator; Draftsman]</author>
<author lc="n86099875" viaf="52700">Coelho, Paulo</author>
</authors>
<orderBy>hold desc</orderBy>
<input type="stdnbr">9780754073963</input>
<!-- Snip -->
</classify>
我使用过 XML,但使用的是 PHP,而不是 C#,所以我对它很陌生,关于这个的教程到处都有不同的东西,让我对做什么和如何做感到困惑。 我只是想从 XML 中得到这些东西:
- 书名(在工作元素中)
- 书籍作者(在工作元素中)
- 图书的 ISBN(在输入元素中 - 类型 stdnbr)
- 最受欢迎的 DDC(在推荐中 > ddc > mostPopular - 属性 [nsfa])
但是通过我在这里和其他论坛上看到的示例,我得到了 NullReferenceException。
代码:
PS:这不是家庭作业。
public frmAddItem(string xml)
{
InitializeComponent();
string itemName = null, itemAuth = null, itemISBN = null;
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(xml);
string itemName = xdoc.Element("classify").Descendants("work").Where(s => s.Attributes() == "title");
string itemAuth = xdoc.Element("classify").Descendants("work").Attributes("author").ToString();
string itemISBN = xdoc.Element("classify").Descendants("input").ToString();
txtTitle.Text = itemName;
txtAuth.Text = itemAuth;
txtISBN.Text = itemISBN;
string itemDDC = xdoc.Element("ddc").Descendants("latestEdition").Attributes("sfa");
}
EDIT Duplicate:提到的重复链接与我的 XML 字符串不同/相似。它使用了一种不同的方法,如问题开头所述,该方法不起作用。
【问题讨论】:
-
请看 XML 的结构,它的不同。我试过了,它没有用。
-
请举一个你实际尝试过的例子。这里只是一个猜测,你知道什么是 xml 命名空间吗?您是否尝试过指定命名空间?
-
我只是将代码添加到我的主要问题中。
-
我已将 System.Xml.Linq 添加到代码中。
标签: c# xml linq linq-to-xml