繁体   English   中英

设置特定xmlNode的值

[英]Setting value of specific xmlNode

目前,我正在使用ac#Windows窗体应用程序,但是存在以下问题:

我有下面列出的xml:

  <new>
    <Company></Company>
    <DateTime></DateTime>
    <Message></Message>
    <Status><Status>
  </new>
  <new>
    <Company></Company>
    <DateTime></DateTime>
    <Message></Message>
    <Status><Status>
  </new>
  <new>
    <Company></Company>
    <DateTime></DateTime>
    <Message></Message>
    <Status><Status>
  </new>
  <new>
    <Company></Company>
    <DateTime></DateTime>
    <Message></Message>
    <Status><Status>
  </new>
  <new>
    <Company></Company>
    <DateTime></DateTime>
    <Message></Message>
    <Status><Status>
  </new>

我正在得到这样的数据:

    XDocument doc = XDocument.Load(Globals.pathNotifFile);
    var notifDateTime = doc.Descendants("DateTime");
    var message = doc.Descendants("Message");
    var company = doc.Descendants("Company");
    var sendStatus = doc.Descendants("Status");

    var dateTimeCollection = new List<String>();
    var messageCollection = new List<String>();
    var companyCollection = new List<String>();
    var statusCollection = new List<String>();

    foreach (var dateTimeOfNotification in notifDateTime)
    {
        dateTimeCollection.Add(dateTimeOfNotification.Value);
    }

    foreach (var messages in message)
    {
        messageCollection.Add(messages.Value);
    }

    foreach (var companys in company)
    {
        companyCollection.Add(companys.Value);
    }

    foreach (var isSent in sendStatus)
    {
        statusCollection.Add(isSent.Value);
    }

    return Tuple.Create(dateTimeCollection, messageCollection, companyCollection, statusCollection);

我正在用xml文件的数据执行此操作

        Tuple<List<String>, List<String>, List<String>, List<String>> t = GetDataFromFile();
        List<String> dateTimeCollection = t.Item1;
        List<String> messageCollection = t.Item2;
        List<String> companyCollection = t.Item3;
        List<String> statusCollection = t.Item4;

        foreach (var notifDateTime in dateTimeCollection)
        {
            int index = dateTimeCollection.IndexOf(notifDateTime);
            if (Int32.Parse(statusCollection[index]) == 1 || statusCollection[index] == string.Empty)
            {
                if (notifDateTime != string.Empty)
                {
                    if (Convert.ToDateTime(notifDateTime) == DateTime.Now)
                    {
                        SendMessageToUser(messageCollection[index], companyCollection[index]);
                    }
                }
            }
        }

之后,在SendMessageToUser中,我正在发送消息,并且得到响应1,2或3,但是我的问题是要获取必须在其中写入状态的确切节点。 我用来写状态的函数是:

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(Globals.pathNotifFile);

    XmlNode commentsElement = doc.SelectSingleNode("Status");
    commentsElement.InnerText = status.ToString();

    doc.Save(Globals.pathNotifFile);

因此,在doc.SelectSingleNode((“ Status”))中,我必须放置选定的节点并对其进行更新。 任何想法我该怎么做

我会解析下面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication49
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("new").Select(x => new {
                company = (string)x.Element("Company"),
                dateTime = (DateTime)x.Element("DateTime"),
                message = (string)x.Element("Message"),
                status = (string)x.Element("Status")
            }).ToList();
        }

    }
}

首先,您应该将解析文件的方式更改为如下所示:

var newsDatas = xdoc.Descendants("new")
                .Select(
                    element =>
                        new 
                        {
                            Company = element.Element("Company").Value,
                            DateTime = element.Element("DateTime").Value,
                            Message = element.Element("Message").Value,
                            Node = element
                        });

然后遍历解析的树并更新相关NodeStatus

foreach (var newsData in newsDatas) 
{
    // .. You logic
    SendMessageToUser(newsData.Message, newsData.Company);

    string status = ....;
    newsData.Node.Element("Status").Value = status;
}

最后,保存XDocument:

doc.Save(Globals.pathNotifFile);

只需直接回答您的问题而无需修改任何代码-如果您要使用xpath选择特定的节点,也可以这样:

doc.SelectSingleNode("//new[1]/Status");

当然,您可以输入所需的任何索引(而不是基于零的索引),而不是“ 1”

编辑:正如您在评论中所述,您没有考虑序列化/反序列化,我强烈建议您尝试使用它。 为了使您着手定义数据,如下所示:

[Serializable]
public class root
{
    [System.Xml.Serialization.XmlElementAttribute("new")]
    public Node[] @new { get; set; }
}

[Serializable]
public class Node
{
    public string Status { get; set; }
    public string Company { get; set; }
    //other properties
}

现在,您可以执行以下操作:

static void Main(string[] args)
{
    var data = Deserialize();
    //do your logic on normal object
    Serialize(data);


}

static root Deserialize()
{
    using (var file = File.Open("test.txt", FileMode.Open))
    {
        XmlRootAttribute xRoot = new XmlRootAttribute();
        xRoot.ElementName = "root";
        xRoot.IsNullable = true;
        var xmlSerializer = new XmlSerializer(typeof(root), xRoot);
        return (root)xmlSerializer.Deserialize(file);
    }
}

static void Serialize(root data)
{
    using (var file = File.Create("result.txt"))
    {
        var xmlSerializer = new XmlSerializer(typeof(root));
        xmlSerializer.Serialize(file, data);
    }
}

只是一个例子,当然这是一个巨大的话题,您可以在SO和其他网站上找到很多例子

暂无
暂无

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

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