Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using an XDocument to build an Xml document in a known structure. The structure I am trying to build is as follows:

<request xmlns:ns4="http://www.example.com/a" xmlns:ns3="http://www.example.com/b" xmlns:ns2="http://www.example.com/c" >
    <requestId>d78d4056-a831-4c7d-a357-d14402f623fc</requestId>
    ....
</request>

Notice the "xmlns:nsX" attributes.

I am trying, without success, to add these attributes to my "request" element.

XNamespace ns4 = XNamespace.Get("http://www.example.com/a");
XNamespace ns3 = XNamespace.Get("http://www.example.com/b");
XNamespace ns2 = XNamespace.Get("http://www.example.com/c");

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "no"),
    new XElement("request",
        new XAttribute("ns4", ns4),
        new XAttribute("ns3", ns3),
        new XAttribute("ns2", ns2),
        new XElement("requestId", Guid.NewGuid())
     )
);

However, this produces the following:

<request ns4="http://www.example.com/a" ns3="http://www.example.com/b" ns2="http://www.example.com/c">
  <requestId>38b07cfb-5e41-4d9a-97c8-4740c0432f11</requestId>
</request>

How do I add the namespace declarations correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
493 views
Welcome To Ask or Share your Answers For Others

1 Answer

Do you mean:

new XAttribute(XNamespace.Xmlns + "ns4", ns4),
new XAttribute(XNamespace.Xmlns + "ns3", ns3),
new XAttribute(XNamespace.Xmlns + "ns2", ns2),

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...