@@ -375,26 +375,49 @@ protected override XmlWriter CreateRewriter(StringBuilder buffer)
375375 }
376376 protected override string PostprocessXaml ( string xaml )
377377 {
378- xaml = RemoveXmlns ( xaml ) ;
379-
378+ xaml = ExtractXmlns ( xaml ) ;
380379 xaml = RemoveOptions ( xaml ) ;
381380
382381 return xaml ;
383382 }
384383
385- private static string RemoveXmlns ( string xaml )
384+ private static string ExtractXmlns ( string xaml )
386385 {
387- var namespaces = new [ ]
388- {
389- "http://schemas.microsoft.com/winfx/2006/xaml/presentation" ,
390- "http://schemas.microsoft.com/winfx/2006/xaml" ,
391- } ;
392- return Regex . Replace ( xaml , @"\s+xmlns(:(?<prefix>\w+))?=""(?<uri>[^""]+)""" , m =>
386+ // extract/remove all xmlns declarations from the xaml,
387+ // and add them at the start, like so:
388+ // xmlns:this="example.com"
389+ // ...
390+ //
391+ // <!-- rest of xaml... -->
392+
393+ // some well known xmlns are also skipped:
394+ bool SkipWellKnownXmlns ( KeyValuePair < string , string > x ) =>
395+ // skip well known xmlnses that are just assumed
396+ // check prefix too, since default name(url) can also be used for platform conditionals, and we should not ignore those
397+ x is not { Key : "" , Value : "http://schemas.microsoft.com/winfx/2006/xaml/presentation" } &&
398+ x is not { Key : "x" , Value : "http://schemas.microsoft.com/winfx/2006/xaml" } ;
399+
400+ var xmlns = new Dictionary < string , string > ( ) ;
401+
402+ xaml = Regex . Replace ( xaml , @"\s+xmlns(?<prefix>:\w+)?=\""(?<name>[^""]+)""" , m =>
393403 {
394- return namespaces ? . Contains ( m . Groups [ "uri" ] . Value ) == true
395- ? null
396- : m . Value ;
404+ if ( xmlns . TryAdd ( m . Groups [ "prefix" ] . Value . TrimStart ( ':' ) , m . Groups [ "name" ] . Value ) )
405+ {
406+ // ignoring xmlns re-definitions in nested node for now
407+ }
408+
409+ return string . Empty ;
397410 } ) ;
411+
412+ if ( xmlns . Where ( SkipWellKnownXmlns ) . ToArray ( ) is { Length : > 0 } injectables )
413+ {
414+ xaml = string . Join ( "\n " , injectables
415+ . OrderBy ( x => x . Key )
416+ . Select ( x => $ "xmlns{ ( string . IsNullOrEmpty ( x . Key ) ? null : $ ":{ x . Key } ") } =\" { x . Value } \" ")
417+ ) + "\n ...\n \n " + xaml ;
418+ }
419+
420+ return xaml ;
398421 }
399422
400423 private static string RemoveOptions ( string xaml )
0 commit comments