c# - 添加具有数据类型属性的新 XElement

标签 c# linq xelement

您好,我有一个 xml 文件:

<?xml version="1.0"?>
<TreeList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Columns>
    <Column>
      <ColumnName>123</ColumnName>
      <ColumnType>Bound</ColumnType>
    </Column>
  </Columns>
  <Nodes>
    <Node Id="0" ParentId="-1">
      <NodeData>
        <Cell xsi:type="xsd:string">Node1</Cell>
      </NodeData>
    </Node>
    <Node Id="1" ParentId="0">
      <NodeData>
        <Cell xsi:type="xsd:string">Node11</Cell>
      </NodeData>
    </Node>
  </Nodes>
</TreeList>

我需要添加新的 XElement:

<Node Id="xx" ParentId="yy">
  <NodeData>
    <Cell xsi:type="xsd:string">NewNode</Cell>
  </NodeData>
</Node>

我的问题出在 XElement 的“xsi:type="xsd:string"部分。我怎样才能像这样设置 XAttribute?

我试过以下:

    public static void AdNewNode(string filePath, string id, string parentId, string value)
    {
        XElement xml = XElement.Load(filePath);
        XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
        XNamespace xsd = "http://www.w3.org/2001/XMLSchema";
        XAttribute attribute1 = new XAttribute(xsd + "string", string.Empty);
        XAttribute attribute2 = new XAttribute(xsi + "type", attribute1.ToString());

        XElement innerNode = new XElement("NodeData", 
                        new XElement("Cell",attribute2, attribute1, value));
        XElement elemnet = new XElement("Node", new XAttribute("Id", id), new XAttribute("ParentId", parentId), innerNode);

        xml.Add(elemnet);
   }

这是结果:

<Node Id="2" ParentId="1">
  <NodeData>
    <Cell p3:type="p0:string=&quot;&quot;" p4:string="" xmlns:p4="http://www.w3.org/2001/XMLSchema" xmlns:p3="http://www.w3.org/2001/XMLSchema-instance">New Node</Cell>
  </NodeData>
</Node> 

有人可以帮助我吗?

最佳答案

"xsd:string" 只是普通字符串,因此您应该能够像这样构造 xsi:type 属性:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XAttribute attribute = new XAttribute(xsi+"type", "xsd:string");

然后随便给它的父元素添加属性:

XElement innerNode = new XElement("NodeData",
                        new XElement("Cell", attribute, value));
XElement elemnet = new XElement("Node", 
                        new XAttribute("Id", id), 
                        new XAttribute("ParentId", parentId), 
                        innerNode);

关于c# - 添加具有数据类型属性的新 XElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30421544/

相关文章:

c# - Blazor Textfield Oninput 用户键入延迟

c# - 在 Entity Framework 中创建多对多联结表

C# 如何在运行时使用 XElement 使用 Dynamic Linq 创建自定义(动态)类

C# linq - 在运行时更改选定的字段

c# - 调用 format-number XPath 函数时,收到错误 : "Namespace Manager or XsltContext needed."

unicode - XElement 和 UTF-8 问题

c# - 未引用库时 Visual Studio 选择了错误的构造函数?

c# - 在同一方法中使用多个等待的效果?

c# - 在这种情况下,如何通过使用 lambda 或 linq 来避免使用嵌套的 foreach 语句?

C#:当派生类及其基类都实现 IEnumerable 时,在派生迭代器类上使用 LINQ