【问题标题】:create new attributes from dynamically created textboxes从动态创建的文本框创建新属性
【发布时间】:2014-08-15 07:21:43
【问题描述】:

我正在尝试通过在选择列表框项时获取面板内动态创建的文本框的值来为所选节点创建新属性。相信你没有听懂我刚才所说的,所以我给你一张照片让你有一个想法。

所以我重新加载xml文件后的问题我在节点内看到了这个东西

d3p1:DisplayFormat="" xmlns:d3p1="gh"

这是正在运行的代码

if (addEl.Count != 0)
{
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load(xml);

    XmlNode pnode = xDoc.DocumentElement.SelectSingleNode("//Class[@Name='" + currentClass + "']/Property[@Id=" + pList.SelectedItem + "]");
    for (int i = 0; i < availableProperties.SelectedItems.Count; i++)
    {
        string selecteItem = availableProperties.SelectedItem.ToString();
        Control[] controls = table2.Controls.Find("txt" + selecteItem, true);

        foreach (Control item in controls)
        {
            foreach (string n in addEl)
            {
                    pnode.Attributes.Append(xDoc.CreateAttribute(n, item.Text));
                    xDoc.Save(xml);
                    ok = true;
            }
        }
    }
 }

要求的 xml 结构。对不起,我忘了放这个

<Root>
  <Class Name="ECMInstruction" Style="Top">
    <Entity Id="1" Name="DocumentInformation" />
    <Entity Id="2" Name="CustomerInformation" />
    <Property Id="1" Name="DocumentTitle">
    </Property>
    <Property Id="2" Name="DateCreated">
      <Lists>
        <ListName>ws_Users</ListName>
        <ListName>dfdfdfd</ListName>
      </Lists>
    </Property>
    <Property Id="3" Name="Deadline">
    </Property>
  </Class>
  <Class Name="AlphaCertificationsIndividual" Style="Top">
    <Entity Id="1" Name="DocumentInformation" />
    <Property Id="1" Name="DocumentTitle">
    </Property>
    <Property Id="2" Name="DateCreated">
      <Lists>
        <ListName>ws_Users</ListName>
        <ListName>dfdfdfd</ListName>
      </Lists>
    </Property>
    <Property Id="3" Name="Deadline">
    </Property>
  </Class>
</Root>

【问题讨论】:

  • 添加您正在操作的 XML 会有很大帮助。我的猜测是;您需要在正确的命名空间中创建新属性。 -> xDoc.CreateAttribute(n, item.Text) 需要一个“命名空间”,而不仅仅是属性名称和值。
  • 没有没有命名空间。只是文本框中的属性名称和值。我刚刚将xml结构添加到问题中
  • 为什么人们投票结束这个问题?

标签: c# xml xpath


【解决方案1】:

而不是这个

pnode.Attributes.Append(xDoc.CreateAttribute(n, item.Text));

试试这个,使用适当的属性名称和值。

pnode.Attributes.Append(xDoc.CreateAttribute("MyNewAttrib")); 
pnode.Attributes["MyNewAttrib"].Value = "newval";

【讨论】:

    【解决方案2】:

    CreateAttribute() 没有overload that accept attribute value as parameter,因此您可以像这样在一行中执行此操作:

    pnode.Attributes.Append(xDoc.CreateAttribute(n, item.Text));
    

    specifies namespace URI of the attribute 上面的第二个参数,这就是为什么你得到了不需要的前缀属性。您需要稍后按照其他答案中的建议分配属性值:

    pnode.Attributes.Append(xDoc.CreateAttribute(n));
    pnode.Attributes[n].Value = item.Text;
    

    【讨论】:

      猜你喜欢
      • 2011-09-10
      • 2013-06-19
      • 1970-01-01
      • 2012-02-01
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多