Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
758 views
in Technique[技术] by (71.8m points)

c# - How can I write xml with a namespace and prefix with XElement?

This may be a beginner xml question, but how can I generate an xml document that looks like the following?

<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
    <ci:field1>test</ci:field1>
    <ca:field2>another test</ca:field2>
</root>

If I can get this to be written, I can get the rest of my problem to work.

Ideally, I'd like to use LINQ to XML (XElement, XNamespace, etc.) with c#, but if this can be accomplished easier/better with XmlDocuments and XmlElements, I'd go with that.

Thanks!!!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here is a small example that creates the output you want:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        XNamespace ci = "http://somewhere.com";
        XNamespace ca = "http://somewhereelse.com";

        XElement element = new XElement("root",
            new XAttribute(XNamespace.Xmlns + "ci", ci),
            new XAttribute(XNamespace.Xmlns + "ca", ca),
                new XElement(ci + "field1", "test"),
                new XElement(ca + "field2", "another test"));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...