1

非常感谢您阅读我的问题。

这是我的 xml 文件。(对于节点 Songs,有很多名为 Song 的子节点)

<?xml version="1.0" encoding="utf-8" ?>
<xmlData>
    <version>1.0</version>
    <Songs>
        <Song>
            <artist>mic</artist>
            <track>2</track>
            <column>happy</column>
            <date>14</date>
        </Song>
        <Song>
            <artist>cool</artist>
            <track>2</track>
            <column>work</column>
            <date>4</date>
        </Song>
    </Songs>
</xmlData>

阅读xml,我使用以下代码:

        XmlDocument doc = new XmlDocument();
        doc.Load(xmlFilePath);

        XmlNode versionNode = doc.SelectSingleNode(@"/xmlData/version");
        Console.WriteLine(versionNode.Name + ":\t" + versionNode.InnerText);

        XmlNode SongsNode = doc.SelectSingleNode(@"/xmlData/Songs");
        Console.WriteLine(SongsNode.Name + "\n");

        XmlDocument docSub = new XmlDocument();
        docSub.LoadXml(SongsNode.OuterXml);

        XmlNodeList SongList = docSub.SelectNodes(@"/Songs/Song");

        if (SongList != null)
        {
            foreach (XmlNode SongNode in SongList)
            {
                XmlNode artistDetail = SongNode.SelectSingleNode("artist");
                Console.WriteLine(artistDetail.Name + "\t: " + artistDetail.InnerText);

                XmlNode trackDetail = SongNode.SelectSingleNode("track");
                Console.WriteLine(trackDetail.Name + "\t: " + trackDetail.InnerText);

                XmlNode columnDetail = SongNode.SelectSingleNode("column");
                Console.WriteLine(columnDetail.Name + "\t: " + columnDetail.InnerText);

                XmlNode dateDetail = SongNode.SelectSingleNode("date");
                Console.WriteLine(dateDetail.Name + "\t: " + dateDetail.InnerText + "\n");

            }
        }

它似乎工作。但是如何将更改写入 xml 文件?也许,我会更改 Song 中的一些 childNode,并可能通过艺术家关键字删除整个 chindNode。

有没有可能像这个函数 bool DeleteSongByArtist(string sArtist); bool ChangeNodeInSong(字符串 sArtist,字符串 sNodeName,字符串值);

因为“阅读解决方案”是“XmlDucoment”,所以最好使用“XmlDocument”“更改解决方案”

但是,如果您有更好的想法来阅读和更改 xml 文件,请给我示例代码...请不要写解决方案的名称,例如“Ling to xml”...实际上,我做了很多睾丸,但失败了。

4

5 回答 5

4

欢迎来到 Stackoverflow!

您可以简单地通过设置新的.Value或在您的情况下更改节点.InnerText

样本

// change the node
trackDetail.InnerText = "NewValue"
// save the document
doc.Save(xmlFilePath);

更多信息

于 2012-04-18T18:11:20.223 回答
1

您需要使用 XmlWriter。最简单的方法是这样的......

using(XmlWriter writer = new XmlWriter(textWriter))
{
   doc.WriteTo(writer);
}

其中 textWriter 是您初始化的文本编写器。

实际上,忘记那个...最简单的方法是打电话给...

doc.Save(xmlFilePath);

要按艺术家名称删除艺术家,请添加以下方法:

    bool DeleteSongByArtist(XmlDocument doc, string artistName)
    {
        XmlNodeList SongList = doc.SelectNodes(@"/Songs/Song");
        if (SongList != null)
        {
            for (int i = SongList.Count - 1; i >= 0; i--)
            {
                if (SongList[i]["artist"].InnerText == artistName && SongList[i].ParentNode != null)
                {
                    SongList[i].ParentNode.RemoveChild(SongList[i]);
                }
            }

        }
    }

您可能希望对其进行更多清理以使其更具弹性。当您调用它时,将您的初始代码更改为这样。不要创建subDocument您想要使用整个 XmlDocument 的文件。

    XmlDocument doc = new XmlDocument();
    doc.Load(xmlFilePath);

    XmlNode versionNode = doc.SelectSingleNode(@"/xmlData/version");
    Console.WriteLine(versionNode.Name + ":\t" + versionNode.InnerText);

    XmlNode SongsNode = doc.SelectSingleNode(@"/xmlData/Songs");
    Console.WriteLine(SongsNode.Name + "\n");

    XmlNodeList SongList = doc.SelectNodes(@"/Songs/Song");

    if (SongList != null)
    {
        foreach (XmlNode SongNode in SongList)
        {
            XmlNode artistDetail = SongNode.SelectSingleNode("artist");
            Console.WriteLine(artistDetail.Name + "\t: " + artistDetail.InnerText);

            XmlNode trackDetail = SongNode.SelectSingleNode("track");
            Console.WriteLine(trackDetail.Name + "\t: " + trackDetail.InnerText);

            XmlNode columnDetail = SongNode.SelectSingleNode("column");
            Console.WriteLine(columnDetail.Name + "\t: " + columnDetail.InnerText);

            XmlNode dateDetail = SongNode.SelectSingleNode("date");
            Console.WriteLine(dateDetail.Name + "\t: " + dateDetail.InnerText + "\n");

        }
    }
于 2012-04-18T18:11:53.060 回答
0

请不要写解决方案的名称,例如“Ling to xml”……实际上,我做了很多睾丸,但都失败了。

我仍然认为,这是开始使用 Linq2Xml 的好时机。如果您不喜欢它,请忽略它。

XDocument xDoc = XDocument.Load(new StringReader(xml));

//Load Songs
var songs = xDoc.Descendants("Song")
                .Select(s => new
                {
                    Artist = s.Element("artist").Value,
                    Track = s.Element("track").Value,
                    Column = s.Element("column").Value,
                    Date = s.Element("date").Value,
                })
                .ToArray();

//Delete Songs
string songByArtist="mic";
xDoc.Descendants("Song")
    .Where(s => s.Element("artist").Value == songByArtist)
    .Remove();
string newXml = xDoc.ToString();
于 2012-04-18T19:02:31.413 回答
0

你可以做

        XmlNodeList SongList = doc.SelectNodes(@"//Songs/Song");

// 告诉它选择文档中任意位置的 Songs 节点。这比

        doc.SelectNodes(@"/document/level1/music/Songs")

请注意,上述声明显然不是针对您的 xml,而是为了证明 //
使用 // 消除了对 docSub 文档和 SongsNode 元素的需要。要添加然后删除一首歌曲,只需使用以下命令

        XmlDocument doc = new XmlDocument();
        XmlElement ea = doc.SelectSingleNode("//songs");
        XmlElement el = doc.CreateElement("song");
        XmlElement er;
        ea.AppendChild(el);
        //doing my work with ea
        //you could use innerxml.
        el.InnerXml = "<artist>Judas Priest</artist><track>7</track><column>good</column><date>1</date>";
        //or you can treat each node as above
        er = doc.CreateElement("Name");
        el.AppendChild(er);
        er.InnerText = "The Ripper";
        //but you don't nead this song any more?
        ea.RemoveChild(el);
        //so it's gone.

这就是它的全部内容。

于 2012-04-18T19:05:43.127 回答
0

您无法保存更改,因为您对一个全新的文档进行了更改!

您可能打算执行以下操作:

XmlNode SongsNode = doc.SelectSingleNode(@"/xmlData/Songs");
Console.WriteLine(SongsNode.Name + "\n");

// Don't make a new XmlDocument here! Use your existing one
XmlNodeList SongList = SongsNode.SelectNodes(@"/Song");

此时SongList仍是住在里面 doc。现在当你打电话时:

doc.Save(xmlFilePath);

您的更改将按您的预期保存。

如果您要删除符合特定条件的节点:

// Use XPath to find the matching node
XmlNode song = SongsNode.SelectSingleNode(@"/Song[artist='" + artist + "']");

// Remove it from its Parent
SongsNode.RemoveChild(song);

如果您要添加新节点:

// Create the new nodes using doc
XmlNode newSong = doc.CreateElement("Song");

XmlNode artist = doc.CreateElement("artist");
artist.InnerText = "Hello";

// Begin the painstaking process of creation/appending
newSong.AppendChild(artist);

// rinse...repeat...

// Finally add the new song to the SongsNode
SongsNode.AppendChild(newSong);
于 2012-04-18T18:24:07.890 回答