【问题标题】:Replace attribute value in XML (attrubute path variable)替换 XML 中的属性值(属性路径变量)
【发布时间】:2018-04-19 16:28:36
【问题描述】:

我正在处理一个 XML 文档,其中包含类似于以下结构的结构:

<SW.Blocks.OB ID="$">
<AttributeList>
<ObjectList>
  <MultilingualText ID="$" CompositionName="Comment">
    <ObjectList>
      <MultilingualTextItem ID="$" CompositionName="Items">
        <AttributeList>
          <Culture>en-US</Culture>
          <Text />
        </AttributeList>
      </MultilingualTextItem>
      <MultilingualTextItem ID="$" CompositionName="Items">
        <AttributeList>
          <Culture>nl-NL</Culture>
          <Text />
        </AttributeList>
      </MultilingualTextItem>
      <MultilingualTextItem ID="$" CompositionName="Items">
        <AttributeList>
          <Culture>de-DE</Culture>
          <Text />
        </AttributeList>
      </MultilingualTextItem>
    </ObjectList>
  </MultilingualText>
</ObjectList>
</SW.Blocks.OB>

我正在搜索属性 ID。这个属性可以出现在任何地方。 我已经可以找到那些 ID 的值了

        XmlTextReader reader = new XmlTextReader(@"Main.xml");
        while (reader.Read())
        {
            reader.MoveToContent();
            string test = reader.GetAttribute("ID");

            if (test == "$")
            {
             MessageBox.Show(test);
            } 
        }

但我无法改变它们。 目标:无论在哪里都能找到 ID,并将该属性的值替换为“值”。

谁能帮帮我?我也已经尝试过 Xdocument 和 Xmldocument。我想不通。

【问题讨论】:

    标签: c# xml xmldocument xmlreader


    【解决方案1】:

    使用 xml linq

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    
    namespace ConsoleApplication13
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
    
                List<XElement> ids = doc.Descendants().Where(x => x.Attribute("ID") != null).ToList();
    
                int indNo = 1;
                foreach (XElement id in ids)
                {
                    id.Attribute("ID").SetValue(indNo++);
                }
    
    
    
            }
    
    
        }
    
    }
    

    【讨论】:

    • 感谢您提供此解决方案。这个解决方案对我有用!
    【解决方案2】:

    我相信使用XmlDocumentXPathNavigator会更容易

    您加载您的文档,然后使用 XPath 浏览它,然后更改您需要的值。

    例如::

    XmlDocument _soapEnvelopeXml = new XmlDocument();
    _soapEnvelopeXml.Load(".xml");
    XPathNavigator _xmlNav = _soapEnvelopeXml.FirstChild.CreateNavigator().SelectSingleNode(WebServiceEnum.MAIN_CIL_TAG);
    
            _xmlNav.CreateNavigator().SelectSingleNode("*[local-name()='BUID']").SetValue(buid);
            _xmlNav.CreateNavigator().SelectSingleNode("*[local-name()='CustomerNumber']").SetValue(customerNum);
    

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      相关资源
      最近更新 更多