2009-09-14 16 views

risposta

3

ho trovato questo post: http://www.biglist.com/lists/xsl-list/archives/200106/msg01225.html che utilizza la seguente XSLT in XML trattino e anche sorta attributi:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

    <xsl:output method="xml" indent="yes"/> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="/"> 
    <xsl:apply-templates/> 
    </xsl:template> 

    <xsl:template match="*"> 
    <xsl:copy> 
     <!-- Sort the attributes by name. --> 
     <xsl:for-each select="@*"> 
     <xsl:sort select="name(.)"/> 
     <xsl:copy/> 
     </xsl:for-each> 
     <xsl:apply-templates/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="text()|comment()|processing-instruction()"> 
    <xsl:copy/> 
    </xsl:template> 

</xsl:stylesheet> 

non l'ho ancora provato, ma molto probabilmente continuerò a XSLT a fare la formattazione per me.

+0

Questo è grande per ordina gli attributi xml, come posso ordinare anche i child di un tag? – Natim

7

Stavo cercando un'utilità simile e non ho trovato quello che stavo cercando, quindi ne ho appena scritto uno. È molto semplice (e non include gli attributi nell'ordinamento dei nodi), ma funziona.

Forse sarà utile per gli altri .. È il GitHub.

Ecco un po 'dalla pagina GitHub ...

USAGE: sortxml.exe [options] infile [outfile] 

    infile  The name of the file to sort, etc. 
    outfile  The name of the file to save the output to. 
       If this is omitted, then the output is written to stdout. 

OPTIONS: 

    --pretty Ignores the input formatting and makes the output look nice. 
    --sort  Sort both the nodes and attributes. 
    --sortnode Sort the nodes. 
    --sortattr Sort the attributes. 

(prefix an option with ! to turn it off.) 

Il default è di uscita nodi bella e ordinati e gli attributi. Ecco un esempio:

> type sample.xml 
<?xml version="1.0" encoding="utf-8" ?><root><node value="one" attr="name"/></root> 

> sortxml.exe sample.xml 
<?xml version="1.0" encoding="utf-8"?> 
<root> 
    <node attr="name" value="one" /> 
</root> 
10

mi è piaciuto di questo strumento: https://xmlsorter.codeplex.com/

È possibile ordinare per nome tag e gli attributi. Mi piace usarlo prima di confrontare alcuni file XML.

XML Sorter main window

+0

Questo non caricarebbe nemmeno il file XML. Trovato un errore "XML non valido". Impossibile gestire il tag doctype. Una volta rimosso ha funzionato. – ScrappyDev

+0

Questo ha funzionato per me per un rapido test di un paio di file con oltre 7K di linee e con una struttura xml semi-complessa, quindi sono inizialmente impressionato. Nessun errore. Un download, lancio ed esecuzione facili e veloci. Una cosa da notare è che consente "ordina attributi" e "ordina attributi specifici" e dove scegli quelli che vuoi. Puoi controllare entrambe le opzioni che sembrano sovrapposte. –

+0

Sono "Sort attributes" e "Sort * by * specific attributes", molto diversi. Il primo ordina gli attributi per ogni riga, il secondo ordina tutte le righe in base al contenuto di un attributo specifico. Quest'ultimo è molto pratico, penso. – Gertsen

2

Fuori di frustrazione con Visual Studio che sembra riordinare & riscrittura EDMX-files (Entity Framework) per tutto il tempo (si veda anche questo Uservoice), ho scritto qualche LINQPad-codice per riordinare roba. È tuttavia facile (e ovvio) utilizzare al di fuori di LinqPad.

Ordina gli elementi per tipo di elemento (tag), quindi per il valore dell'attributo-elemento "Nome", e quindi per altre cose per cercare di renderlo deterministico (diverso xml, ma stesso significato , è [di solito] stesso output - vedi codice).

Inoltre, ordina gli attributi. Si noti che semanticamente XML-attributi possono non avere (rilevante) ordine, ma testualmente che fanno, e sistemi di controllo versione ancora li considerano solo testo ...

(Si noti che non riuscite a rimuovere diversi pseudonimi, accennato nel Entity Framework edmx file regenerating differently amongst team)

void Main() 
{ 
    XDocument xdoc = XDocument.Load(@"\\filepath1\file1.edmx"); 

    var orderedElements = CopyAndSortElements(xdoc.Elements()); 

    var newDoc = new XDocument(); 
    newDoc.Add(orderedElements); 
    newDoc.Save(@"\\filepath1\file1.Ordered.edmx"); 
} 

public IEnumerable<XElement> CopyAndSortElements(IEnumerable<XElement> elements) 
{ 
    var newElements = new List<XElement>(); 
    // Sort XElements by Tag & name-attribute (and some other properties) 
    var orderedElements = elements.OrderBy(elem => elem.Name.LocalName) // element-tag 
            .ThenByDescending(elem => elem.Attributes("Name").Count()) // can be 0, more than 1 is invalid XML 
            .ThenBy(elem => (elem.Attributes("Name").Any() ? elem.Attributes("Name").First().Value.ToString() : string.Empty)) 
            // in case of no Name-Attributes, try to sort by (number of) children 
            .ThenBy(elem => elem.Elements().Count()) 
            .ThenBy(elem => elem.Attributes().Count()) 
            // next line may vary for textually different but semantically equal input when elem & attr were unordered on input, but I need to restrain myself... 
            .ThenBy(elem => elem.ToString()); 
    foreach (var oldElement in orderedElements) 
    { 
     var newElement = new XElement(oldElement.Name); 
     var orderedAttrs = oldElement.Attributes().OrderBy(attr => attr.Name.LocalName).ThenBy(attr => attr.Value.ToString()); 
     newElement.Add(orderedAttrs); 
     newElement.Add(CopyAndSortElements(oldElement.Elements())); 
     newElements.Add(newElement); 
    } 
    return newElements; 
} 

PS: Abbiamo finito con un XSLT, che qualcun altro ha scritto allo stesso tempo. Penso che sia più facile/migliore nel processo di costruzione di tutti. Ma forse/spero che questo sia di qualche utilità per qualcuno.

+0

Cosa hai finito per usare xslt? –

+0

uh, guarda questo - toglie i valori dai nodi come " valore" –

0

Mi sono imbattuto in questo post quando ho cercato di capire come ordinare ed edmx file. La mia soluzione è basata sulla soluzione Arvo Bowens trovato https://stackoverflow.com/a/19324438/212241

void Main() 
{ 
    XDocument xdoc = XDocument.Load(@"C:\git\Nvision\Source\NvisionEntities\NvisionModel.edmx"); 
    Sort(xdoc.Root); 
    xdoc.Save(@"C:\git\Nvision\Source\NvisionEntities\NvisionModel.edmx"); 
} 

public void Sort(XElement source, bool bSortAttributes = true) 
{ 
    //Make sure there is a valid source 
    if (source == null) throw new ArgumentNullException("source"); 

    //Sort attributes if needed 
    if (bSortAttributes) 
    { 
     List<XAttribute> sortedAttributes = source.Attributes().OrderBy(a => a.ToString()).ToList(); 
     sortedAttributes.ForEach(a => a.Remove()); 
     sortedAttributes.ForEach(a => source.Add(a)); 
    } 

    //Sort the children IF any exist 
    List<XElement> sortedChildren = source.Elements().OrderBy(elem => elem.Attributes("Name").Any() ? elem.Attributes("Name").First().Value.ToString() : string.Empty).ToList(); 
    if (source.HasElements) 
    { 
     source.RemoveNodes(); 
     sortedChildren.ForEach(c => Sort(c)); 
     sortedChildren.ForEach(c => source.Add(c)); 
    } 
} 
Problemi correlati