Domanda

Date le (esemplare - vero e proprio margine di profitto può essere molto più complicato) markup e dei vincoli di seguito elencati, chiunque potrebbe proporre una soluzione (C #) più efficace / efficiente rispetto a piedi l'intero albero per recuperare { "@@ @@ valore1", "valore2 @@ @@", "@@ @@ valore3"}, vale a dire un elenco di token che stanno per essere sostituite quando il markup è effettivamente utilizzato.

Nota. Non ho alcun controllo sul markup, la struttura del markup o il formato / denominazione dei gettoni che vengono sostituiti

<markup>
    <element1 attributea="blah">@@value1@@</element1>
    <element2>@@value2@@</element2>
    <element3>
        <element3point1>@@value1@@</element3point1>
        <element3point2>@@value3@@</element3point2>
        <element3point3>apple</element3point3>
    <element3>
    <element4>pear</element4>
</markup>
È stato utile?

Soluzione

Come su:

    var keys = new HashSet<string>();
    Regex.Replace(input, "@@[^@]+@@", match => {
        keys.Add(match.Value);
        return ""; // doesn't matter
    });
    foreach (string key in keys) {
        Console.WriteLine(key);
    }

Questa:

  • non si preoccupa parsing XML (solo la manipolazione delle stringhe)
  • include solo le / valori unici (non è necessario restituire un MatchCollection con i duplicati che non vogliamo)

Tuttavia, può costruire una stringa più grande, in modo forse solo Matches:

var matches = Regex.Matches(input, "@@[^@]+@@");
var result = matches.Cast<Match>().Select(m => m.Value).Distinct();
foreach (string s in result) {
    Console.WriteLine(s);
}

Altri suggerimenti

ho scritto un rapido prog con il campione, questo dovrebbe fare il trucco.

class Program
    {
        //I just copied your stuff to Test.xml
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load("Test.xml");
            var verbs=new Dictionary<string,string>();
            //Add the values to replace ehre
            verbs.Add("@@value3@@", "mango");
            verbs.Add("@@value1@@", "potato");
            ReplaceStuff(verbs, doc.Root.Elements());
            doc.Save("Test2.xml");
        }

        //A simple replace class
        static void ReplaceStuff(Dictionary<string,string> verbs,IEnumerable<XElement> elements)
        {
            foreach (var e in elements)
            {
                if (e.Elements().Count() > 0)
                    ReplaceStuff(verbs, e.Elements() );
                else
                {
                    if (verbs.ContainsKey(e.Value.Trim()))
                        e.Value = verbs[e.Value];
                }
            }
        }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top