如何检查xml文档是否具有特定的属性列表?

发布于 2024-11-19 14:10:11 字数 746 浏览 1 评论 0原文

我正在尝试使用 C# 和 xml,我正在尝试读取一个 XML 文件,我想验证“NumberOfDays”、“NumberOfBooks”、“NumberOfExam”、“CurrentDate”是否存在(如果缺失)。我想将它们添加到这些值中。

我有以下 xmldocument :

<?xml version="1.0" encoding="utf-8" ?>
<MySample>
  <Content>
    <add  key="NumberOfDays" value="31"  />
    <add  key="NumberOfBooks" value="20"  />
    <add  key="NumberOfExam" value="6"  />
    <add  key="CurrentDate" value="15 - Jul - 2011"  />
  </Content>
</MySample>

用 C# 编写一个示例应用程序,

我正在使用--------Edit--------

谢谢 AresAvatar你的回应。

但如果该值存在,我想更新其值,即如果

<add  key="NumberOfExam" value=""  />

我想将值更改为 6

i am experimenting with C# and xml, i am trying to read a XML file i want to validate if "NumberOfDays" , "NumberOfBooks", "NumberOfExam", "CurrentDate" are existing, if missing. i want to add them with there values.

i have the following xmldocument :

<?xml version="1.0" encoding="utf-8" ?>
<MySample>
  <Content>
    <add  key="NumberOfDays" value="31"  />
    <add  key="NumberOfBooks" value="20"  />
    <add  key="NumberOfExam" value="6"  />
    <add  key="CurrentDate" value="15 - Jul - 2011"  />
  </Content>
</MySample>

i am writing a sample application in c# using

--------Edit--------

thank you AresAvatar for your responce.

but if the value exists i would like to update its value i.e. if let's say

<add  key="NumberOfExam" value=""  />

i want to change the value to 6

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请持续率性 2024-11-26 14:10:11

您可以像这样获取存在哪些节点的列表:

// Get a list of which nodes exist
XmlDocument doc = new XmlDocument();
doc.LoadXml(myXml);
List<string> existingNodes = new List<string>();
XmlNodeList bookNodes = doc.SelectNodes("/MySample/Content/add");
foreach (XmlNode nextNode in bookNodes)
{
    foreach (XmlAttribute nextAttr in nextNode.Attributes)
        existingNodes.Add(nextAttr.InnerText);
}

您可以像这样添加缺少的节点:

// Add nodes
XmlNode addRoot = doc.SelectSingleNode("/MySample/Content");
XmlElement addme = doc.CreateElement("add");
addme.SetAttribute("NumberOfDays", "31");
addRoot.AppendChild(addme);

您可以像这样设置现有节点的值:

// Update a node
foreach (XmlNode nextNode in bookNodes)
{
    foreach (XmlAttribute nextAttr in nextNode.Attributes)
    {
        switch (nextAttr.Name)
        {
            case "NumberOfDays":
                ((XmlElement)nextNode).SetAttribute("value", "31");
                break;
            // etc.
        }
    }
}

You can get a list of which nodes exist like this:

// Get a list of which nodes exist
XmlDocument doc = new XmlDocument();
doc.LoadXml(myXml);
List<string> existingNodes = new List<string>();
XmlNodeList bookNodes = doc.SelectNodes("/MySample/Content/add");
foreach (XmlNode nextNode in bookNodes)
{
    foreach (XmlAttribute nextAttr in nextNode.Attributes)
        existingNodes.Add(nextAttr.InnerText);
}

You can add missing nodes like this:

// Add nodes
XmlNode addRoot = doc.SelectSingleNode("/MySample/Content");
XmlElement addme = doc.CreateElement("add");
addme.SetAttribute("NumberOfDays", "31");
addRoot.AppendChild(addme);

You can set the value of existing nodes like this:

// Update a node
foreach (XmlNode nextNode in bookNodes)
{
    foreach (XmlAttribute nextAttr in nextNode.Attributes)
    {
        switch (nextAttr.Name)
        {
            case "NumberOfDays":
                ((XmlElement)nextNode).SetAttribute("value", "31");
                break;
            // etc.
        }
    }
}
面如桃花 2024-11-26 14:10:11

首先,如果您可以控制生成的 XML(如果您自己创建),请避免使用此模式:

<?xml version="1.0" encoding="utf-8" ?>
<MySample>
  <Content>
    <add  key="NumberOfDays" value="31"  />
    <add  key="NumberOfBooks" value="20"  />
    <add  key="NumberOfExam" value="6"  />
    <add  key="CurrentDate" value="15 - Jul - 2011"  />
  </Content>
</MySample>

使用该模式会更容易:

<?xml version="1.0" encoding="utf-8" ?>
    <MySample>
      <Content>
       <Adds>
        <NumberOfDays>31<NumberOfDays/>
        <NumberOfBooks>20<NumberOfBooks/>
        <NumberOfExam>6<NumberOfExam/>
        <CurrentDate>5 - Jul - 2011<CurrentDate/>
       </Adds>
      </Content>
    </MySample>

然后:

XmlDocument doc = new XmlDocument();
doc.Load("YourXmlPath");
XmlNode firstNode = doc["MySample"];
if(firstNode != null)
{
    XmlNode secondNode = firstNode["Content"];
    if(secondNode != null)
    {
        XmlNode thirdNode = secondNode["Adds"];
        if(thirdNode != null)
        {
            if(thirdNode["NumberOfDays"] == null) //The "NumberOfDays" node does not exist, we create it.
            {
                XmlElement newElement = doc.CreateElement("NumberOfDays");
                newElement.InnerXml = 31;
                thirdNode.AppendChild(newElement);                    
            }
            //Do the same for the other nodes...
        }
    }
}
doc.Save("YourXmlPath");

只需记住在每个节点上检查 null ,或者将整个块进入 try/catch。

并在完成更改后保存 XML。

XmlDocument.Load() 函数将 XML 加载到内存中,因此您可以检查任何节点,而无需进行“盲循环”。

First of all, if you have control over the generated XML (if you make it yourself), avoid using this schema:

<?xml version="1.0" encoding="utf-8" ?>
<MySample>
  <Content>
    <add  key="NumberOfDays" value="31"  />
    <add  key="NumberOfBooks" value="20"  />
    <add  key="NumberOfExam" value="6"  />
    <add  key="CurrentDate" value="15 - Jul - 2011"  />
  </Content>
</MySample>

It's much easier to use with that schema:

<?xml version="1.0" encoding="utf-8" ?>
    <MySample>
      <Content>
       <Adds>
        <NumberOfDays>31<NumberOfDays/>
        <NumberOfBooks>20<NumberOfBooks/>
        <NumberOfExam>6<NumberOfExam/>
        <CurrentDate>5 - Jul - 2011<CurrentDate/>
       </Adds>
      </Content>
    </MySample>

And then:

XmlDocument doc = new XmlDocument();
doc.Load("YourXmlPath");
XmlNode firstNode = doc["MySample"];
if(firstNode != null)
{
    XmlNode secondNode = firstNode["Content"];
    if(secondNode != null)
    {
        XmlNode thirdNode = secondNode["Adds"];
        if(thirdNode != null)
        {
            if(thirdNode["NumberOfDays"] == null) //The "NumberOfDays" node does not exist, we create it.
            {
                XmlElement newElement = doc.CreateElement("NumberOfDays");
                newElement.InnerXml = 31;
                thirdNode.AppendChild(newElement);                    
            }
            //Do the same for the other nodes...
        }
    }
}
doc.Save("YourXmlPath");

Just remember to check for null on every node, or put the whole block into a try/catch.

And to save the XML once you did your changes.

XmlDocument.Load() function loads the XML in memory, so you can check for any node without making "blind loops".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文