使用XElement进行XML检索 [英] XML Retrieval with XElement

查看:53
本文介绍了使用XElement进行XML检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我正在尝试更改两个兄弟姐妹同名的xml标签的名称。

示例:

考虑以下部分xml文档



< book>

< name> XML及相关技术< / name>

< author> Atul Kahate< / author>

< author> Achyut Godbole< / author>

< pages> 500< / pages>

< ; / book>



这里有两个名称作者的标签,它们是彼此的兄弟姐妹,所以一个标签的名称应该更改为author2。

我正在使用XElement课程。

请帮助我。



提前致谢。

Hello,
I am trying to change the name of xml tag where two siblings are having same name.
Example:
consider following part of xml document

<book>
<name>XML and related technologies</name>
<author> Atul Kahate</author>
<author>Achyut Godbole</author>
<pages>500</pages>
</book>

Here there are 2 tags with name author which are siblings of each other so name of one tag should be changed to say author2.
I am using XElement class.
Please help me.

Thanks in advance.

推荐答案

您可以使用以下方法更新Duplicate xml节点

You can update Duplicate xml nodes by using the below method
public static bool UpdateDuplicateXml(string xmlFilePath)
        {
            try
            {
                XDocument xml = XDocument.Load(xmlFilePath);
                var dubs = xml.Descendants().Where(x => x.Name == "author");
                var xElements = dubs as XElement[] ?? dubs.ToArray();
                if (xElements.Count() > 1)
                {
                    for (int index = 0; index < xElements.Length; index++)
                    {

                        if (index == 0)
                        {
                            XElement xElement = xElements[index];
                            xElement.Name = xElement.Name;
                        }
                        else
                        {
                            XElement xElement = xElements[index];
                            int newIndex = index + 1;
                            xElement.Name = xElement.Name + newIndex.ToString();
                        }

                    }
                }
                xml.Save(xmlFilePath);
                return true;
            }
            catch(Exception exception)
            {
                return false;
            }
        }



希望这有帮助


Hope this helps


这篇关于使用XElement进行XML检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆