gpt4 book ai didi

c# - 无法读取简单的 xml 文件

转载 作者:数据小太阳 更新时间:2023-10-29 02:04:10 26 4
gpt4 key购买 nike

我知道这看起来像是一个愚蠢的简单问题,但我还是会问的。我一直在尝试阅读这个 xml 文件:

<Songs>
<song>
<TrackID>1666</TrackID>
<Name>What's the Matter Here?</Name>
<Artist>10,000 Maniacs</Artist>
<AlbumArtist>10,000 Maniacs</AlbumArtist>
<Composer>Natalie Merchant/Robert Buck</Composer>
<Album>In My Tribe</Album>
<Genre>Rock</Genre>
<Kind>MPEG audio file</Kind>
<Size>9318485</Size>
<TotalTime>291134</TotalTime>
<TrackNumber>1</TrackNumber>
<Year>1987</Year>
<DateModified>2005-03-09T07:31:09Z</DateModified>
<DateAdded>2007-07-20T17:21:36Z</DateAdded>
<BitRate>256</BitRate>
<SampleRate>44100</SampleRate>
<Comments> </Comments>
<PersistentID>54F22391EB807F38</PersistentID>
<TrackType>File</TrackType>
<Location></Location>
</song>
<song>
<TrackID>1666</TrackID>
<Name>What's the Matter Here?</Name>
<Artist>10,000 Maniacs</Artist>
<AlbumArtist>10,000 Maniacs</AlbumArtist>
<Composer>Natalie Merchant/Robert Buck</Composer>
<Album>In My Tribe</Album>
<Genre>Rock</Genre>
<Kind>MPEG audio file</Kind>
<Size>9318485</Size>
<TotalTime>291134</TotalTime>
<TrackNumber>1</TrackNumber>
<Year>1987</Year>
<DateModified>2005-03-09T07:31:09Z</DateModified>
<DateAdded>2007-07-20T17:21:36Z</DateAdded>
<BitRate>256</BitRate>
<SampleRate>44100</SampleRate>
<Comments> </Comments>
<PersistentID>54F22391EB807F38</PersistentID>
<TrackType>File</TrackType>
<Location></Location>
</song>
</Songs>

我正在使用这段代码来阅读上面的内容:

    private static void LoadSongsFromITunes(string xmlFile)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
string album=null ;
string artists=null ;
string genres=null ;
string year=null ;
string duration=null ;

try
{
using (XmlReader reader = XmlReader.Create(xmlFile, settings))
{
string xmlContent;

while (reader.Read())
{
if (reader.NodeType != XmlNodeType.Element) continue;
xmlContent = "";
string name=null;
if (reader.Name == "Name")
{
name = reader.ReadString().ToString();
}
if (reader.Name == "Artist")
{
artists = reader.ReadString().ToString();
}
if (reader.Name == "Album")
{
album = reader.ReadString().ToString();
}
if (reader.Name == "Genre")
{
genres = reader.ReadString().ToString();
}
if (reader.Name == "Year")
{
year = reader.ReadString();
}
if (reader.Name == "Duration")
{
duration = reader.ReadString().ToString();
}
Console.WriteLine(name);
}
}
}
catch
{

}

但是,读取器似乎只返回 null。我已经通过调试器跨过了代码,但我不太明白这段代码有什么问题。P.S:有人可以提供更好的方法吗?比如使用 xml 链接之类的?

最佳答案

LINQ 到 XML:

var doc = XDocument.Parse(xml);

var result = doc
.Root.Elements("song")
.Select(e =>
new { Name = (string)e.Element("Name"), Artist = (string)e.Element("Artist") });

foreach (var val in result)
{
Console.WriteLine(val);
}

关于c# - 无法读取简单的 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8617792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com