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
663 views
in Technique[技术] by (71.8m points)

c# - Creating XDocument with xsi:schemaLocation namespace

I need to create the following XML and I'm trying to do this using XDocument. However, I'm having trouble specifying the name spaces.

<AssessmentOrderRequest
    xsi:schemaLocation="http://ns.hr-xml.org/2007-04-15 http://ns.hr-xml.org/2_5/HR-XML-2_5/StandAlone/AssessmentOrderRequest.xsd"
    xmlns="http://ns.hr-xml.org/2007-04-15"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</AssessmentOrderRequest>

This is the sort of code that I'm looking for, however, I can't create attributes with a colon in the name for the xsi:schemaLocation.

return new XDocument(
    new XElement("AssessmentOrderRequest",
        new XAttribute("xsi:schemaLocation", XNamespace.Get("http://ns.hr-xml.org/2007-04-15 http://ns.hr-xml.org/2_5/HR-XML-2_5/StandAlone/AssessmentOrderRequest.xsd")),
        new XAttribute("xmlns", XNamespace.Get("http://ns.hr-xml.org/2007-04-15")),
        new XAttribute(XNamespace.Xmlns + "xsi", XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance"))
    )
);
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is because the xsi is a namespace in itself. You would need to do something like:

        XNamespace xmlns = XNamespace.Get("http://ns.hr-xml.org/2007-04-15");
        XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
        XNamespace schemaLocation = XNamespace.Get("http://ns.hr-xml.org/2007-04-15 http://ns.hr-xml.org/2_5/HR-XML-2_5/StandAlone/AssessmentOrderRequest.xsd");

        return new XDocument(
            new XElement(xmlns + "AssessmentOrderRequest",
                new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                new XAttribute(xsi + "schemaLocation", schemaLocation)
            )
        );

EDIT: Updated with final code that I used to solve the problem. With thanks to the original answer from James.


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

...