Skip to content

XAttribute (LINQ to XML): Elaborate on using the default namespace #44499

@SetTrend

Description

@SetTrend

Type of issue

Missing information

Description

The documentation on "How to create a document with namespaces in C# (LINQ to XML)" doesn't explain how to handle the creation of new XAttribute objects that are supposed to have the enclosing XElement's default namespace applied, e.g.:

<root xmlns="default/namespace">
  <element attribute="value"/>
</root>

Without documentation, there are two options that might be hypothetically applicable for creating the correct XML with LINQ to XML:

  1. XNamespace ns = new XNamespace("default/namespace");
    ...
    new XElement(ns + "element", new XAttribute(ns + "attribute", "value"))
  2. XNamespace ns = new XNamespace("default/namespace");
    ...
    new XElement(ns + "element", new XAttribute("attribute", "value"))

I propose to add an example to the documentation, making clear that XML attributes inherit the enclosing element's default namespace by not prefixing it with the default namespace declaration.

I also created a pull request having one of the examples being amended to include information on how to create XAttribute objects with (a) default namespace, and (b) prefixed namespace applied.


Page URL

https://learn.microsoft.com/en-us/dotnet/standard/linq/create-document-namespaces-csharp

Content source URL

https://github.com/dotnet/docs/blob/main/docs/standard/linq/create-document-namespaces-csharp.md

Document Version Independent Id

e34d6fbd-8233-edcc-d253-def34d2c324f

Article author

@BillWagner

Metadata

  • ID: 525bf456-96f9-3ec5-baa7-231213dff194
  • Service: dotnet-fundamentals

Related Issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions