Skip to content

XML _ XElementFormatter

axunonb edited this page Mar 11, 2022 · 4 revisions

The XElementFormatter formats and outputs XElements.

Syntax Details

{ XElement : xml }

Value formatter name
XElement "xml"

Note:

  • There are no "option" or "format" arguments to the XElementFormatter.
  • Supports XML with namespaces.

Configuration:

none

Examples

Single Level XML

// Process single level xml
var oneLevel= XElement.Parse(
   "<root>" +
     "<FirstName>Joe</FirstName>" +
     "<LastName>Doe</LastName>" +
     "<Dob>1950-05-05</Dob>" +
   "</root>");

var smart = Smart.CreateDefaultSmartFormat()
    .AddExtensions(new XElementFormatter())
    .AddExtensions(new XmlSource());

smart.Format("Mr {FirstName:xml} {LastName:xml}", oneLevel);
// Outputs: "Mr Joe Doe"

Multi Level XML

var twoLevel = XElement.Parse(
   "<root>" +
     "<Person>" +
        "<FirstName>Joe</FirstName>" +
        "<LastName>Doe</LastName>" +
        "<Phone>123-123-1234</Phone>" +
        "</Person>" +
     "<Person>" +
        "<FirstName>Jack</FirstName>" +
        "<LastName>Doe</LastName>" +
        "<Phone>789-789-7890</Phone>" +
     "</Person>" +
  "</root>");

var smart = Smart.CreateDefaultSmartFormat()
    .AddExtensions(new XElementFormatter())
    .AddExtensions(new XmlSource());

// Access xml level by index
smart.Format("{Person[1].FirstName:xml}, Phone: {Person[1].Phone:xml}", twoLevel);
// Outputs: "Jack, Phone: 789-789-7890"

More Elements With The Same Name

var multiFirstName = XElement.Parse(
  "<root>" +
    "<FirstName>Joe</FirstName>" +
    "<FirstName>Jack</FirstName>" +
    "<LastName>Doe</LastName>" +
    "<FirstName>Jim</FirstName>" +
  "</root>");

var smart = Smart.CreateDefaultSmartFormat()
    .AddExtensions(new XElementFormatter())
    .AddExtensions(new XmlSource());

// More xml elements with the same name are treated as a list
// (used together with ConditionalFormatter)
smart.Format("There {FirstName.Count:cond:is {} Doe |are {} Does}", multiFirstName);
// Outputs: "There are 3 Does"

// List FirstNames with ListFormatter
smart.Format("{FirstName:list:|, | and }", multiFirstName);
// Outputs: "Joe, Jack and Jim"
Clone this wiki locally