读奇怪的XML文件

时间:2013-10-03 23:17:18

标签: c# xml linq

我通过这个网站和谷歌进行了搜索,并没有真正找到类似的东西..我遇到的大部分例子都是更正常,更清洁的标准?我只需要弄清楚如何读取Name =,Handle =和Tweet =。谢谢你的帮助

到目前为止,我所拥有的只是:

doc = XDocument.Load("twitterTrio.xml");    
var temp = doc.Descendants("tweets")....

xml我试图阅读:

<?xml version="1.0" encoding="utf-8"?>
<dtvTwitter>
  <tweets>
    <RcsTweet xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="NFL on ESPN" Handle="@ESPNNFL" Tweet="So @RGIII can pass, run and now he can BEAT BOX??  (MUST SEE VIDEO) --&gt; http://t.co/sexsrtskfZ" ImageUrl="http://a0.twimg.com/profile_images/3573179175/26a4fd77256691aedab2ecbc60c7b86c_normal.jpeg" />
    <RcsTweet xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="NFL Retweet" Handle="@NFLRT" Tweet="RT @NOTSportsCenter: BREAKING: There's a reason #Jets coach Rex Ryan keeps naming Mark Sanchez starter: he's blind. http://t.co/zEPKqfAV1o" ImageUrl="http://a0.twimg.com/profile_images/378800000203929393/ef2529f3f226d69c0731c7469f1c51ba_normal.jpeg" />
    <RcsTweet xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="ProFootballTalk" Handle="@ProFootballTalk" Tweet="Bernard Pollard says Justin Hunter can destroy a defense, be a star and help the Titans win a championship http://t.co/GPJcJXXqvg" ImageUrl="http://a0.twimg.com/profile_images/2390753568/qzhbfg9lgfrkmkrt4l4u_normal.jpeg" />
  </tweets>
</dtvTwitter>

2 个答案:

答案 0 :(得分:3)

    XmlNodeList elemList = doc.GetElementsByTagName("RcsTweet");
    for (int i = 0; i < elemList.Count; i++)
    {
        string name = elemList[i].Attributes["Name"].Value;
        string handle = elemList[i].Attributes["Handle"].Value;
        string tweet = elemList[i].Attributes["Tweet"].Value;
    }

答案 1 :(得分:2)

我通常更喜欢使用XML序列化,让.Net处理意外情况

public class dtvTwitter
{
    public tweets tweets{get;set;}
}
public class tweets
{
    [XmlElement("RcsTweet")]
    public List<RcsTweet> RcsTweets { get; set; }

}
public class RcsTweet
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlAttribute]
    public string Tweet { get; set; }

    [XmlAttribute]
    public string Handle { get; set; }
}

然后只是:

        XmlSerializer ser = new XmlSerializer(typeof(dtvTwitter));
        StreamReader sr = new StreamReader("myfile.xml");
        dtvTwitter val = (dtvTwitter)ser.Deserialize(sr);

获取反序列化的图表