如何替换所有“值”在带有“0.0”的 XML 文档中使用 C#(最好是 LINQ)?

发布于 2024-10-20 12:40:15 字数 1790 浏览 5 评论 0原文

这不是家庭作业;而是家庭作业。我需要这个来进行单元测试。

示例输入:1234Hello......

示例输出:0.00.0......< ;/行>

您可以假设文档以 开头,并且父节点具有名为 的子节点。您不知道节点 ab 等的名称。

额外加分:如何使用任意格式良好的“自由格式”XML 来实现此操作?

我已经用正则表达式尝试过这个:)但没有运气。我可以让它“在右边非贪婪”,但不能在左边。感谢您的帮助。

编辑:这是我尝试过的:

    private static string ReplaceValuesWithZeroes(string gridXml)
    {
        Assert.IsTrue(gridXml.StartsWith("<row>"), "Xml representation must start with '<row>'.");
        Assert.IsTrue(gridXml.EndsWith("</row>"), "Xml representation must end with '<row>'.");

        gridXml = "<deleteme>" + gridXml.Trim() + "</deleteme>"; // Fake parent.
        var xmlDoc = XDocument.Parse(gridXml);
        var descendants = xmlDoc.Root.Descendants("row");
        int rowCount = descendants.Count();
        for (int rowNumber = 0; rowNumber < rowCount; rowNumber++)
        {
            var row = descendants.ElementAt(0);
            Assert.AreEqual<string>(row.Value /* Does not work */, String.Empty, "There should be nothing between <row> and </row>!");
            Assert.AreEqual<string>(row.Name.ToString(), "row");

            var rowChildren = row.Descendants();
            foreach (var child in rowChildren)
            {
                child.Value = "0.0"; // Does not work.
            }
        }

        // Not the most efficient but still fast enough.
        return xmlDoc.ToString().Replace("<deleteme>", String.Empty).Replace("</deleteme>", String.Empty);
    }

This is not a homework; I need this for my unit tests.

Sample input: <rows><row><a>1234</a><b>Hello</b>...</row><row>...</rows>.

Sample output: <rows><row><a>0.0</a><b>0.0</b>...</row><row>...</rows>.

You may assume that the document starts with <rows> and that parent node has children named <row>. You do not know the name of nodes a, b, etc.

For extra credit: how to make this work with an arbitrary well-formed, "free-form" XML?

I have tried this with a regex :) without luck. I could make it "non-greedy on the right", but not on the left. Thanks for your help.

EDIT: Here is what I tried:

    private static string ReplaceValuesWithZeroes(string gridXml)
    {
        Assert.IsTrue(gridXml.StartsWith("<row>"), "Xml representation must start with '<row>'.");
        Assert.IsTrue(gridXml.EndsWith("</row>"), "Xml representation must end with '<row>'.");

        gridXml = "<deleteme>" + gridXml.Trim() + "</deleteme>"; // Fake parent.
        var xmlDoc = XDocument.Parse(gridXml);
        var descendants = xmlDoc.Root.Descendants("row");
        int rowCount = descendants.Count();
        for (int rowNumber = 0; rowNumber < rowCount; rowNumber++)
        {
            var row = descendants.ElementAt(0);
            Assert.AreEqual<string>(row.Value /* Does not work */, String.Empty, "There should be nothing between <row> and </row>!");
            Assert.AreEqual<string>(row.Name.ToString(), "row");

            var rowChildren = row.Descendants();
            foreach (var child in rowChildren)
            {
                child.Value = "0.0"; // Does not work.
            }
        }

        // Not the most efficient but still fast enough.
        return xmlDoc.ToString().Replace("<deleteme>", String.Empty).Replace("</deleteme>", String.Empty);
    }

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

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

发布评论

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

评论(4

北风几吹夏 2024-10-27 12:40:15
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        foreach (XmlElement el in doc.SelectNodes("//*[not(*)]"))
            el.InnerText = "0.0";
        xml = doc.OuterXml;

或者对非空文本节点更有选择性:

        foreach (XmlText el in doc.SelectNodes("//text()[.!='']"))
            el.InnerText = "0.0";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        foreach (XmlElement el in doc.SelectNodes("//*[not(*)]"))
            el.InnerText = "0.0";
        xml = doc.OuterXml;

or to be more selective about non-empty text nodes:

        foreach (XmlText el in doc.SelectNodes("//text()[.!='']"))
            el.InnerText = "0.0";
水水月牙 2024-10-27 12:40:15
XDocument xml = XDocument.Load(myXmlFile);

foreach (var element in xml.Descendants("row").SelectMany(r => r.Elements()))
{
    element.Value = "0.0";
}

请注意,这种对“后代('行')”的一般搜索效率不是很高,但它满足了“任意格式”的要求。

XDocument xml = XDocument.Load(myXmlFile);

foreach (var element in xml.Descendants("row").SelectMany(r => r.Elements()))
{
    element.Value = "0.0";
}

Note that this general search for "Desscendants('row')" is not very efficient--but it satisfies the 'arbitrary format' requirement.

绝不服输 2024-10-27 12:40:15

您应该查看 HTML Agility Pack。它允许您将 html 文档视为格式良好的 xml 文档,因此您可以解析它并更改值。

You should take look at HTML Agility Pack. It allows you to treat html documents as well-formed xml's, therefore you can parse it and change values.

柠栀 2024-10-27 12:40:15

我认为你可以在 C# 中使用 Regex.Replace 方法。我使用下面的正则表达式来替换所有 XML 元素值:

[>]+[a-zA-Z0-9]+[<]+

这基本上会匹配以 '>'{一些文本字母或数字}'<'

我能够在 Notepad++ 中成功使用它。您也可以使用它编写一个小程序。

I think you can use Regex.Replace method in C#. I used the below regex to replace all the XML elements values:

[>]+[a-zA-Z0-9]+[<]+

This will basically match text starting with a '>'{some text alphabets or number}'<'.

I was able to use this successfully in Notepad++. You can write a small program as well using this.

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