【问题标题】:Modify a xml node with spacing and quotes as attricutes修改带有空格和引号作为属性的xml节点
【发布时间】:2014-01-08 08:29:57
【问题描述】:

我正在尝试访问 XML 的子节点,但我的第一个 XML 节点具有间距和引号作为属性。

 var xml = @"<Envelope xsd "http">
            <Catalog>
                <Price>
                  <Value Default ="yes">P1</Value>
                </Price>
            </Catalog>
        </Envelope>";

我试图将 Default 的属性值从“yes”更改为“1”,但节点总是返回 null。

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var node = doc.SelectSingleNode("/*/Catalog/Price/Value");

有什么想法吗?

【问题讨论】:

    标签: c# xml xsd nodes


    【解决方案1】:

    我认为这不是有效的 xml,您可能是指以下内容

    using System;
    using System.Globalization;
    using System.Xml;
    
    namespace ConsoleApplication9
    {
        class Program
        {
            private static void Main(string[] args)
            {
                //Valid XML
                string xml = @"<Envelope xsd='http'>
                              <Catalog>
                                 <Price>
                                   <Value Default='yes'>P1</Value>
                                </Price>
                              </Catalog>
                             </Envelope>";
                var doc = new XmlDocument();
                doc.LoadXml(xml);
    
                //Select the Value Node
                XmlNode node = doc.SelectSingleNode("/*/Catalog/Price/Value");
    
                //Set the Default attribute to 1
                node.Attributes["Default"].Value = 1.ToString(CultureInfo.InvariantCulture);
    
                //Check the output
                Console.WriteLine(doc.InnerXml.ToString(CultureInfo.InvariantCulture));
    
                //Press enter to exit
                Console.ReadLine();
            }
        }
    }
    

    只是说。

    【讨论】:

    【解决方案2】:

    http://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx

    使用 // 而不是 /* 因为 // 获取文档的根

    【讨论】:

    • 试过了,但我猜斯图尔特是对的。根从一开始就无效。
    【解决方案3】:

    这可能看起来有点硬编码,但它应该可以工作:

      XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        Namespace ns= "http"; //set the namespace of the root node here
    
        //the following is where you change the value to 1
    
     doc.Document.Descendants(ns+"Envelope").FirstorDefault().Descendants(ns+"Catalog").Descendants(ns+"Price").FirstorDefault().Elements("Value").Attribute("Default").SetValue("1");
    

    另外,xml 看起来有点不对劲,正如有人提到的,根节点需要更正。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 2017-10-29
      • 1970-01-01
      • 2012-05-05
      相关资源
      最近更新 更多