生成xml字符串并传入命名空间

时间:2013-07-02 17:50:48

标签: c# xml asp.net-mvc

我在添加空格名时生成xml字符串时遇到问题。这就是我想要生成我的xml的方式

xml示例:

<Feedback xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Record>
        <ID>2FAC636E-F96C-4465-9272-760BAF73C0DF</QRCodeID>
        <SubID>10B5236C-47FD-468D-B88D-D789CA0C663A</SubmissionID>
        <UserID>1</UserID>
        <Page>1</Page>
    </Record>
    <Record>
        <ID>219C462B-B874-4408-AFBA-CA727922D50F</QRCodeID>
        <SubID>10B5236C-47FD-468D-B88D-D789CA0C663A</SubmissionID>
        <UserID>1</UserID>
        <Page>2</Page>
    </Record>
</Feedback>

我的代码现在是什么样的:

XDocument xdoc = new XDocument(
            new XElement("Feedback xmlns:i='http://www.w3.org/2001/XMLSchema-instance'",
                new XElement("Record",
                    new XElement("ID", idGuid),
                    new XElement("SubID", subGuid),
                    new XElement("UserID", 2),
                    new XElement("Page", pages)
                    )
            )
        );

当我运行它时会在"Feedback xmlns:i='http://www.w3.org/2001/XMLSchema-instance'"处抛出一个错误,它不喜欢字符''

3 个答案:

答案 0 :(得分:0)

查看this MSDN page,它解释了您需要知道的所有内容

答案 1 :(得分:0)

我很确定你需要使用Namespaces

这是尝试使用整个字符串创建一个无效的标记。

答案 2 :(得分:0)

documentation here表明以下内容应该有效:

XDocument xdoc = new XDocument(
    new XElement("Feedback",
        new XAttribute(XNamespace.Xmlns + "i", "http://www.w3.org/2001/XMLSchema-instance"),
        new XAttribute(XNamespace.Xmlns + "j", "http://schemas.sitename.com/2013/03/Project.Models"),
        new XElement("Record",
            new XElement("ID", idGuid),
            new XElement("SubID", subGuid),
            new XElement("UserID", 2),
            new XElement("Page", pages)
        )
    )
);