C# 使用 Xpath 更改 XML 值 [英] C# Change XML value using Xpath

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

问题描述

谁能帮帮我?我对 C# 有点陌生,但到了那里.我已经设置了一个任务来从 XML 文件中检索数据、更改数据并使用 Xpath 将其保存在另一个位置.

can anyone help me? I am kind of new to C# but getting there. I have been set a task to retrieve data from an XML file, change the data, and save it in another location using Xpath.

我认为我的代码有点"正确,但我在语法和特定元素的路径上苦苦挣扎.我已经包含了一个经过简化但元素布局相同的 XML 文件示例.

I think I have the code 'kind of' correct but I am struggling with the syntax with the path to the specific element. I have included a sample of the XML file which has been simplified but the layout of the elements is the same.

<?xml version="1.0" encoding="utf-8"?>
<Data SomeData which linked to a wepage.>
    <DeviceId>Sometext</DeviceId>
    <Inputs>
        <a:ImageInput>
            <a:Cal>
                <a:Volt1></Volt1>
                <a:Volt2></Volt2>
            </a:Cal>
            <a:Name>Name1</a:Name>
        </a:ImageInput>
        <a:ImageInput>
            <a:Cal>
                <a:Volt1></Volt1>
                <a:Volt2></Volt2>
            </a:Cal>
            <a:Name>Name2</a:Name>  <!-- Need to change this element -->
        </a:ImageInput>
    </Inputs>
</Data>

如您所见,我需要更改 a:Name 元素,但要在第二个 a:ImageInput 元素内更改.我一直在寻找答案,但我只找到了一些示例,其中 Xpath 更改了根元素的一部分.

As you can see I need to change the a:Name element but within the second a:ImageInput element. I have looked for answers but I have only found examples where Xpath has changed part of a root element.

这是我在 Main() 方法中使用的代码.

Here is my code which is used within the Main() method.

public static void ChangeFileXPath()//Changes the value of the node using Xpath
    {
        XmlDocument xmld = new XmlDocument();
        xmld.Load(@"C:\ProgramData\Oxford Instruments NanoAnalysis\Calibration\mics_simulator.xml");

        XmlElement name2 = (XmlElement)xmld.SelectSingleNode("/MicsModule/Inputs/a:ImageInput[@a:Name='BSE']");
        if (name2 != null)
        {
            name2.SetAttribute("a:Name", "{{16}}");
        }

        string AmmendedFile = @"C:\ProgramData\Oxford Instruments NanoAnalysis\XXXX NewXMLReader\Xpath_Mics_Sim.xml";
        xmld.Save(AmmendedFile);
    }

任何帮助将不胜感激.感谢您的关注.

Any help would be very appreciated. Thank you for looking.

推荐答案

/Data/Inputs/a:ImageInput[@a:Name='Name2']

即寻找具有 attribute a:Name 和特定值的 a:ImageInput 元素.

That is looking for a:ImageInput elements with an attribute a:Name with the specific value.

但是 XML 有一个 element a:Name.

But the XML has an element a:Name.

或者作为一个元素,使用 XPath

Either treat as an element, with XPath

/Data/Inputs/a:ImageInput/a:Name[text()='Name2']

然后在代码中设置找到的元素的值.或者切换 XML 以使用属性.

and then set the value of the found element in code. Or switch the XML to use an attribute.

更新查看了 XML

首先:XML 无效.例如.<a:Volt2></Volt2>:结尾名称需要与开头匹配.

First: the XML is not valid. Eg. <a:Volt2></Volt2>: the closing name needs to match the opening.

第二:虽然技术上 XML 可以在没有命名空间的情况下使用(它们是原始标准的可选扩展),但 .NET 中的 XML 支持将a:"视为需要命名空间声明(这适用于 XmlReader 是所有不同 XML API 的底层解析器:XmlDocumentXPathDocumentXDocument).

Second: while technically XML can be used without namespaces (they are an optional extension to the original standard), the XML support in .NET treats "a:" as needing a namespace declaration (this applies to XmlReader which is the underlying parser for all the different XML APIs: XmlDocument, XPathDocument, and XDocument).

因此,您需要向文档添加 XML 命名空间声明(并更正上述不匹配的结束元素):

So you'll need to add an XML Namespace declaration to the document (and correct the mismatched closing elements noted above):

<?xml version='1.0' encoding='utf-8'?>
<Data xmlns:a='this should be a uri'>
    <DeviceId>Sometext</DeviceId>
    <Inputs>
        <a:ImageInput>
            <a:Cal>
                <a:Volt1></a:Volt1>
                <a:Volt2></a:Volt2>
            </a:Cal>
            <a:Name>Name1</a:Name>
        </a:ImageInput>
        <a:ImageInput>
            <a:Cal>
                <a:Volt1></a:Volt1>
                <a:Volt2></a:Volt2>
            </a:Cal>
            <a:Name>Name2</a:Name>  <!-- Need to change this element -->
        </a:ImageInput>
    </Inputs>
</Data>

鉴于此,XML 将加载,并且可以被操纵.对上述 XPath 进行更正并匹配 XML,结果如下:

Given this the XML will load, and can be manipulated. With corrections to the XPath as above plus matching the XML the following works:

使用系统;使用 System.Xml;

using System; using System.Xml;

class Program
{
    const string Content = @"<?xml version='1.0' encoding='utf-8'?>
<Data xmlns:a='whatever'>
    <DeviceId>Sometext</DeviceId>
    <Inputs>
        <a:ImageInput>
            <a:Cal>
                <a:Volt1></a:Volt1>
                <a:Volt2></a:Volt2>
            </a:Cal>
            <a:Name>Name1</a:Name>
        </a:ImageInput>
        <a:ImageInput>
            <a:Cal>
                <a:Volt1></a:Volt1>
                <a:Volt2></a:Volt2>
            </a:Cal>
            <a:Name>Name2</a:Name>  <!-- Need to change this element -->
        </a:ImageInput>
    </Inputs>
</Data>";
    static void Main(string[] args)
    {
        var xml = new XmlDocument();
        xml.LoadXml(Content);

        XmlNamespaceManager mgr = new XmlNamespaceManager(xml.NameTable);
        mgr.AddNamespace("a", "whatever");
        XmlElement name2 = (XmlElement)xml.SelectSingleNode("/Data/Inputs/a:ImageInput/a:Name[text()='Name2']", mgr);
        if (name2 != null)
        {
            name2.InnerText = "A new value";
        }

        Console.WriteLine(xml.InnerXml);
    }
}

这篇关于C# 使用 Xpath 更改 XML 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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