繁体   English   中英

使用 Xdocument 进行简单的 Xml 解析

[英]Simple Xml parse with Xdocument

我想用 Xdocument 在 windows store 应用程序中解析 xml。

我试过这个,但返回空值:

XDocument xDoc;
string title= "";

xDoc = XDocument.Load(url);

var elements = from x in xDoc.Descendants()
               select new
               {
                   title = x.Descendants("title").First().Value,
               };

foreach (var el in elements)
    _title = title;

xml内容:

<title type='text'>tiitle</title>
<content type='text'> gfgdgdggd</content>
<link rel='related' type='application/atom+xml' href='http....'/>

如何从属性中检索文本?

正如 ZevSpitz 已经提到的,您的 XML 无效。 我修改了一下,以便能够测试我的代码:

<root>
    <title type="text">title</title>
    <content type="text">gfgdgdggd</content>
</root>

您可以使用以下代码从type属性中检索值:

XDocument xDoc = XDocument.Parse(xml);

var types =
    from x in xDoc.Root.Descendants()
    select x.Attribute("type").Value;

在我的情况下, xml声明如下:

private string xml =
    @"<root>
        <title type=""text"">title</title>
        <content type=""text"">gfgdgdggd</content>
    </root>";

如果文件内容相同,您仍然可以使用代码从 URL 加载 XML。

尝试:

var types =
    from e in xDoc.Descendants()
    select (string)e.Attribute("type");

foreach (string type in types) {
    Console.WriteLine(type);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM