【问题标题】:XML-Code Change Value of Node - How is the displayed Code correct?节点的 XML 代码更改值 - 显示的代码如何正确?
【发布时间】:2019-12-17 05:24:54
【问题描述】:

我需要使用 XMLDocument 在 C# 中编写 XML 文件。我提取所需的 XML 文件,只需要插入一些我需要添加的元素。

预期输出应如下所示:

<service>
   <coding>
       <system value="https://somethingichanged" />
         <code value="myvalue" />
    </coding>
</service>

但是,我的输出如下所示:

<service>
    <coding>
         <system>https://somethingichanged</system>
        <code>myvalue</code>
    </coding>
</service>

这是我的代码:

string[] tag = new string[] { "service", "coding", "system", "code", "http://URI"};
XmlElement Service = m_XMLDoc.CreateElement(tag[0], tag[4]);
XmlElement Coding = m_XMLDoc.CreateElement(tag[1], tag[4]);
Service.AppendChild(Coding);

//Fill Element
XmlNode System = m_XMLDoc.CreateNode(XmlNodeType.Element, tag[2], tag[4]);
XmlNode Code = m_XMLDoc.CreateNode(XmlNodeType.Element, tag[3], tag[4]);
System.InnerText = "https://somethingichanged";
Coding.AppendChild(System);

Code.InnerText = myTSS[i].ToString();
Coding.AppendChild(Code);

正确的代码是什么样的?谢谢!

【问题讨论】:

    标签: c# .net xml xmldocument xml-attribute


    【解决方案1】:

    您应该创建属性,而不是 xml 元素。

    所以使用:

    System.Attributes.Append( m_XMLDoc.CreateAttribute("value", "https://somethingichanged"));
    
    Code.Attributes.Append( m_XMLDoc.CreateAttribute("value", myTSS[i].ToString()));
    

    而不是

    System.InnerText = "https://somethingichanged";
    Code.InnerText = myTSS[i].ToString();
    

    【讨论】:

      【解决方案2】:

      .Net LINQ to XML 使得在单个代码语句中实现这一目标变得更加容易。

      c#

      void Main()
      {
          string[] tag = new string[] { "service", "coding", "system", "code", "http://URI"};
      
          XElement xml = new XElement(tag[0],
                              new XElement(tag[1],
                                  new XElement(tag[2], new XAttribute("value", tag[4])),
                                  new XElement(tag[3], new XAttribute("value", "myvalue")))
                              );
      }
      

      输出 XML:

      <service>
        <coding>
          <system value="http://URI" />
          <code value="myvalue" />
        </coding>
      </service>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-08
        • 2019-09-10
        • 2019-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-24
        • 1970-01-01
        相关资源
        最近更新 更多