Skip to content

Commit 677bbc9

Browse files
authored
Using default namespace with System.Xml.Linq.XAttribute explained. (#44501)
1 parent 57b80de commit 677bbc9

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

docs/standard/linq/create-document-namespaces-csharp.md

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: How to create a document with namespaces in C# - LINQ to XML
33
description: Use the XNamespace object in C# to create documents that have default namespaces or namespaces with a prefix.
4-
ms.date: 07/20/2015
4+
ms.date: 01/23/2025
55
ms.topic: how-to
66
---
77

@@ -60,6 +60,8 @@ The following example shows the creation of a document that contains two namespa
6060

6161
By including namespace attributes in the root element, the namespaces are serialized so that `http://www.adventure-works.com` is the default namespace, and `www.fourthcoffee.com` is serialized with a prefix of `fc`. To create an attribute that declares a default namespace, you create an attribute with the name `xmlns`, without a namespace. The value of the attribute is the default namespace URI.
6262

63+
If a default namespace declaration is in scope, it applies to child `XElement` objects by prefixing their local names with the corresponding `XNamespace` object. On the other hand, default namespace declarations do not apply directly to attribute names. So, `XAttribute` objects in the default namespace are defined by *not* prefixing their local name with the corresponding `XNamespace` object.
64+
6365
```csharp
6466
// The http://www.adventure-works.com namespace is forced to be the default namespace.
6567
XNamespace aw = "http://www.adventure-works.com";
@@ -70,8 +72,14 @@ XElement root = new XElement(aw + "Root",
7072
new XElement(fc + "Child",
7173
new XElement(aw + "DifferentChild", "other content")
7274
),
73-
new XElement(aw + "Child2", "c2 content"),
74-
new XElement(fc + "Child3", "c3 content")
75+
new XElement(aw + "Child2", "c2 content",
76+
new XAttribute("DefaultNs", "default namespace"),
77+
new XAttribute(fc + "PrefixedNs", "prefixed namespace")
78+
),
79+
new XElement(fc + "Child3", "c3 content",
80+
new XAttribute("DefaultNs", "default namespace"),
81+
new XAttribute(fc + "PrefixedNs", "prefixed namespace")
82+
)
7583
);
7684
Console.WriteLine(root);
7785
```
@@ -83,8 +91,9 @@ This example produces the following output:
8391
<fc:Child>
8492
<DifferentChild>other content</DifferentChild>
8593
</fc:Child>
86-
<Child2>c2 content</Child2>
87-
<fc:Child3>c3 content</fc:Child3>
94+
<Child2 DefaultNs="default namespace" fc:PrefixedNs="prefixed namespace">c2 content</Child2>
95+
<fc:Child3 DefaultNs="default namespace" fc:PrefixedNs="prefixed namespace">c3 content</fc:Child3>
96+
8897
</Root>
8998
```
9099

0 commit comments

Comments
 (0)