是否可以使用xmlreader更改节点值?

时间:2019-05-22 15:17:28

标签: c# .net xml xmldocument xmlreader

我正在读取大约100mb的XML流,我想替换超过1mb的值。

示例输入

<root>
    <visit>yes</visit>
    <filedata>SDFSFDSDFfgdfgsgdf==(this is 5 mb)</filedata>
    <type>pdf</type>
    <moredata>sssssssssssssss (this 2mb)</moredata>
</root>

预期输出

<root>
    <visit>yes</visit>
    <filedata>REPLACED TEXT</filedata>
    <type>pdf</type>
    <moredata>REPLACED TEXT</moredata>
</root>

这就是我用来读取流以及检查大小的内容:

XmlReader rdr = XmlReader.Create (new System.IO.StringReader (xml));
while (rdr.Read ()) {
    if (rdr?.Value.Length > ONEMEGABYTE) {
        //replace value with "REPLACE TEXT"}
    }

如何替换rdr.Value中的值?

3 个答案:

答案 0 :(得分:1)

您可以将XmlReader子类化以“过滤”出不需要的元素,然后将XmlDocument.Load()与读者一起使用,而不用让它自己创建。

请注意,这将仅排除有问题的标记的 value :如果在Read()循环中放置断点,则会发现<foo>bar</foo>分为三部分: <foo>的NodeType元素没有值,“ bar”的NodeType Text带有空的LocalName,而</foo>是NodeType的EndElement没有值。如果“酒吧”超过了限制长度,则下面的“过滤器”将把<foo>bar</foo>变成<foo></foo>。要基于“酒吧”的长度排除所有<foo>bar</foo>,您需要展望未来。可行,但也许不值得您花时间。希望这里不是必需的。

该类的替代(或附加)可能是带有Func<string, string>的该版本,每个Value都通过:s => (s.Length > MAX_LEN) ? "" : s

据我所知,XmlTextReaderImpl_reader的实际类型)可能会缓存整个文本并反而会降低性能。您可能还需要为此写一些胆量。

public class FilteredXmlReader : XmlReader
{
    public Func<XmlReader, bool> Filter;

    private XmlReader _reader;
    private FilteredXmlReader(TextReader input, Func<XmlReader, bool> filterProc)
    {
        Filter = filterProc;
        _reader = XmlReader.Create(input);
    }

    public static new XmlReader Create(TextReader input, Func<XmlReader, bool> filterProc)
    {
        return new FilteredXmlReader(input, filterProc);
    }

    public override bool Read()
    {
        var b = _reader.Read();

        while (!(bool)Filter?.Invoke(_reader))
        {
            b = _reader.Read();
        }

        return b;
    }

    #region Wrapper Boilerplate

    public override XmlNodeType NodeType => _reader.NodeType;

    public override string LocalName => _reader.LocalName;

    public override string NamespaceURI => _reader.NamespaceURI;

    public override string Prefix => _reader.Prefix;

    public override string Value => _reader.Value;

    public override int Depth => _reader.Depth;

    public override string BaseURI => _reader.BaseURI;

    public override bool IsEmptyElement => _reader.IsEmptyElement;

    public override int AttributeCount => _reader.AttributeCount;

    public override bool EOF => _reader.EOF;

    public override ReadState ReadState => _reader.ReadState;

    public override XmlNameTable NameTable => _reader.NameTable;

    public override string GetAttribute(string name) => _reader.GetAttribute(name);

    public override string GetAttribute(string name, string namespaceURI) => _reader.GetAttribute(name, namespaceURI);

    public override string GetAttribute(int i) => _reader.GetAttribute(i);

    public override string LookupNamespace(string prefix) => _reader.LookupNamespace(prefix);

    public override bool MoveToAttribute(string name) => _reader.MoveToAttribute(name);

    public override bool MoveToAttribute(string name, string ns) => _reader.MoveToAttribute(name, ns);

    public override bool MoveToElement() => _reader.MoveToElement();

    public override bool MoveToFirstAttribute() => _reader.MoveToFirstAttribute();

    public override bool MoveToNextAttribute() => _reader.MoveToNextAttribute();

    public override bool ReadAttributeValue() => _reader.ReadAttributeValue();

    public override void ResolveEntity() => _reader.ResolveEntity();

    #endregion Wrapper Boilerplate
}

用法:

var xml = "<test />";
XmlDocument doc = new XmlDocument();

XmlReader rdr = FilteredXmlReader.Create(new System.IO.StringReader(xml), 
                    r => r?.Value.Length < 20);

var filteredXML = doc.OuterXml;

答案 1 :(得分:0)

以下是使用Xml Reader和Xml Linq进行替换的示例

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


namespace ConsoleApplication29
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);

            while (!reader.EOF)
            {
                if (reader.Name != "visits")
                {
                    reader.ReadToFollowing("visits");
                }
                if (!reader.EOF)
                {
                    XElement visits = (XElement)XElement.ReadFrom(reader);
                    XElement filedata = visits.Element("filedata");
                    filedata.SetValue("New Data");

                }
            }

        }
    }
}

这是我使用的xml

<root>
  <visits>
    <visit>yes</visit>
    <filedata>REPLACED TEXT</filedata>
    <type>pdf</type>
    <moredata>REPLACED TEXT</moredata>
  </visits>
</root>

答案 2 :(得分:0)

我们可以通过使用XmlDocument来实现。获取根节点的所有子节点,然后遍历所有节点-

        XmlDocument Doc = new XmlDocument();
        Doc.Load(@"yourpath.xml");
        XmlNodeList xmlNodelist = Doc.DocumentElement.ChildNodes;
        foreach (XmlNode node in xmlNodelist)
        {
            if(node.InnerText.Length > ONEMEGABYTE)
            {
                node.InnerText = "new value";
            }
        }
        Doc.Save(@"yourpath.xml"); //will replace new changes in the source file.