首页 > 解决方案 > 如何在 C# 中使用 xelement 创建这种类型的 xml

问题描述

这就是我需要的:

<EuropeanSale>
 <VATCore:SubmittersReference>001</VATCore:SubmittersReference>
 <VATCore:CountryCode>AT</VATCore:CountryCode>
 <VATCore:CustomerVATRegistrationNumber>U52375709</VATCore:CustomerVATRegistrationNumber>
 <VATCore:TotalValueOfSupplies>1000</VATCore:TotalValueOfSupplies>
 <VATCore:TransactionIndicator>2</VATCore:TransactionIndicator>
</EuropeanSale>

这是我的代码:

XElement temp= new XElement("EuropeanSale", 
    new XElement("Vat:SubmittersReference", item.SubmittersReference), 
    new XElement("Vat:CountryCode", item.CountryCode), 
    new XElement("CustomerVATRegistrationNumber", item.CustomerVATRegistrationNumber), 
    new XElement("Vat:TotalValueOfSupplies", item.TotalValueOfSupplies), 
    new XElement("Vat:TransactionIndicator", item.TransactionIndicator) );

这是一个例外:

“':' 字符,十六进制值 0x3A,不能包含在名称中。”

标签: c#.netxml

解决方案


您至少需要在父元素中声明命名空间。看看这是否能让你开始:

using System;
using System.Xml.Linq;

public class Program
{
    public static void Main()
    {
        // Create an XML tree in a namespace, with a specified prefix  
        XNamespace ns = "http://example.com";
        XElement root = new XElement("Root", 
                                     new XAttribute(XNamespace.Xmlns + "VATCore", "http://example.com"), 
                                     new XElement(ns + "Child", "child content")
                                    );
        Console.WriteLine(root);
    }
}

以上输出

<Root xmlns:VATCore="http://example.com">
  <VATCore:Child>child content</VATCore:Child>
</Root>

https://dotnetfiddle.net/zedBb3上。


推荐阅读