0

我正在创建一个带有命名空间的 XML,但 url 是用 XAttribute 元素而不是命名空间“前缀”编写的 这是我得到的输出

<xmi:XMI xmlns:uml="http://www.omg.org/spec/UML/20110701"
         xmlns:xmi="http://www.omg.org/spec/XMI/20110701">   
   <xmi:Documentation exporter="Enterprise Architect" exporterVersion="6.5" />  
       <uml:Model xmi:type="{http://www.omg.org/spec/UML/20110701}Model" name="EA_Model">
          <packagedElement xmi:type="{http://www.omg.org/spec/UML/20110701}Package" xmi:id="1212" name="Logical View">
          <packagedElement xmi:type="{http://www.omg.org/spec/UML/20110701}Class" xmi:id="35798" name="MyClass">

但我应该生成这样的东西..

<xmi:XMI xmlns:uml="http://www.omg.org/spec/UML/20110701"
         xmlns:xmi="http://www.omg.org/spec/XMI/20110701">   
   <xmi:Documentation exporter="Enterprise Architect" exporterVersion="6.5" />  
       <uml:Model xmi:type="uml:Model" name="EA_Model">
          <packagedElement xmi:type="uml:Package" xmi:id="1212" name="Logical View">
          <packagedElement xmi:type="uml:Class" xmi:id="35798" name="MyClass">

我的代码:

XNamespace uml = "http://www.omg.org/spec/UML/20110701";
XNamespace xmi = "http://www.omg.org/spec/XMI/20110701";

XElement rootElement = new XElement(xmi + "XMI", new XAttribute(XNamespace.Xmlns + "uml", "http://www.omg.org/spec/UML/20110701"), new XAttribute(XNamespace.Xmlns + "xmi", "http://www.omg.org/spec/XMI/20110701"));
doc.Add(rootElement);

rootElement.Add(new XElement(xmi+"Documentation", new XAttribute("exporter", "Enterprise Architect"), new XAttribute("exporterVersion", "6.5")));

XElement modelNode = new XElement(uml + "Model", new XAttribute(xmi + "type", uml + "Model"), new XAttribute("name", "EA_Model"));
rootElement.Add(modelNode);

XElement logicalViewElement = new XElement("packagedElement", new XAttribute(xmi + "type", uml + "Package"), new XAttribute(xmi + "id", project.Id), new XAttribute("name", "Logical View"));
modelNode.Add(logicalViewElement);

Dictionary<string, XElement> entityNodes = new Dictionary<string, XElement>();
foreach (BusinessEntityDataObject entity in project.BusinessEntities)
{
    XElement entityElement = 
        new XElement("packagedElement", 
           new XAttribute(xmi+"type",uml+"Class"),
           new XAttribute(xmi+"id",entity.Id), 
           new XAttribute("name",entity.Name));
4

1 回答 1

0

而不是将 XNamespace 与字符串值连接起来

 new XAttribute(xmi + "type", uml + "Class")

您应该手动构建属性值:

 new XAttribute(xmi + "type", "uml:Class")

XAttribute构造函数有两个参数 - 第一个期望XName和第二个期望 simple object。当你结合XNamespacestring得到string结果时,它看起来像xmi.ToString() + attributeName,它等于"{http://www.omg.org/spec/XMI/20110701}type"。因此XNodetype 已经定义了从字符串的隐式转换,这个字符串可以转换为XName实例。

在第二种情况下uml + "Class"也组合成 string "{http://www.omg.org/spec/UML/20110701}Class"。但是构造函数的第二个参数应该是 type object,并且该字符串满足该要求,因此没有任何内容被转换为XName并且您将组合字符串作为属性值。

于 2013-10-21T09:41:34.420 回答