System.XML or Regex.Replace?

I am creating a large number of XML documents from a set of values ​​in an Excel file. The only thing that changes for each XML document is the values. I decided that the best way to generate these documents is to make an "XML skeleton" (since the XML format never changes) and then include characters like "&% blahNameblahTest", so I could just re-create a Regex.Replace on each value .

I will transfer this project to another developer, and I am wondering if I should convert the project to generate the XML file manually each time through the System.XML namespace.

The only benefits that I see in this is to ensure that the XML document is correct.

The current method will be more readable than this method, and faster since I create about 1,500 documents.

+3
source share
4 answers

I would stick with your existing method.

However, I would add a link to System.Linq.XMLand do XElement.Parse()the output to ensure that your resulting document is parsed correctly. (The only advantage you mentioned in the System.Xml route!)

+1
source

You can use the method string.Format

string.Format(
@"
   <Parent attribute = \"{0}\">
      <Child>{1}</Child>
   </Parent>
",
"foo",
"bar"
);

This will lead to

   <Parent attribute = "foo">
      <Child>bar</Child>
   </Parent>

which you can send to any stream.

0
source

, XML skelleton XDocument LINQ to XML.

,

public static void Replace(this XDocument haystack, String needle, String replacement)
{
    var query = haystack.Root
                        .DescendantsAndSelf()
                        .Where(xe => !xe.HasElements && xe.Value == needle);
    foreach (XElement item in query)
    {
        item.Value = replacement;
    }
}
0

, , XML.

, , , 1500 .

, , 1500 XML-, , XML, .

, , , , :

<element>$symbol</element>

:

XmlDocument skeleton = new XmlDocument();
skeleton.Load(inputPath);
foreach (XmlElement elm in skeleton.SelectNodes("//*[starts-with(., '$')]"))
{
   elm.InnerText = GetValue(elm.InnerText);
}
skeleton.Save(outputPath);

- XmlReader XmlWriter, , , .

An additional advantage of this approach when used Regex.Replace: it only makes two passes through skeletal XML, once for its analysis and once for its search. If you use a regex, you will look for the skeleton XML from beginning to end once for each value that you replace.

0
source

Source: https://habr.com/ru/post/1741766/


All Articles