【问题标题】:can I use Linq to Xml to alter an XSD?我可以使用 Linq to Xml 来更改 XSD 吗?
【发布时间】:2009-12-29 21:31:05
【问题描述】:

我想修改 XSD 中的一个节点。我想更改此节点中的“名称”值:

<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">

但是,当我尝试通过此代码查找该节点时,我没有收到任何节点或出现错误,具体取决于我的尝试。

xsdDoc.Descendants("element").Where(x => x.Attribute("name").Value == "NewDataSet").Single().SetAttributeValue("name", "newValue");

Linq To Xsd 不是一个选项,因为它看起来像是开源的,这意味着各种繁文缛节(在工作中)。

这是可能的,还是我不走运?

相关(但不相同):Linq to XML - update/alter the nodes of an XML Document

【问题讨论】:

    标签: linq linq-to-xml


    【解决方案1】:

    “xs”命名空间需要一个 XNamespace,然后需要使用 xsdDoc.Descendants(ns+"element")


    XNamespace xs = "http://www.w3.org/2001/XMLSchema";
    doc.Descendants(xs + "element").
        Where(x.Attribute("name") != null 
        &&  x => x.Attribute("name").Value == "NewDataSet").First().
        SetAttributeValue("name", "newValue");
    

    【讨论】:

    • 像这样:“w3.org/2001/XMLSchemaelement”?这似乎不对,但我知道你要去哪里......
    • 啊,像这样:XNamespace xn = "w3.org/2001/XMLSchema"; IEnumerable elems = xsdDoc.Descendants(xn+"element").Where( x => x.Attribute("name").Value == "NewDataSet");
    • 整个 XDocument/X* 命名空间有点奇怪。
    • 它看起来确实正确,但是我第二次在 lambda 上得到一个空引用异常。
    • 如果我用 .Single().SetAttributeValue() 做同样的结果
    【解决方案2】:

    只是猜测,但可能是命名空间问题,请尝试使用 LocalName,就像在这个问题中一样:

    Ignore namespaces in LINQ to XML

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多