【问题标题】:Get and Set XML elements with Namespaces使用命名空间获取和设置 XML 元素
【发布时间】:2014-11-25 12:57:00
【问题描述】:

新手问题。

我没有用过太多的xml,反正也没有这样的东西。我收到了一些如下所示的 XML,其中包含多个命名空间。

我需要读取一些值,然后更新其他值,然后返回带有完整命名空间的修改后的 XML - 不希望它们被删除。

我获得了一些元素的路径,例如 cred/sub/aatrip/items/item[0]/customerInfo/custName

但似乎命名空间很难如此简单地访问这些元素。

有人知道我如何从custPref 读取一些值,例如NON-SMOKING,或者从bossman/zz 获取值CABBAGE

另外,我希望能够设置一个值,例如custName 来表示Mr. X

有什么想法吗?

谢谢。

<?xml version="1.0" encoding="utf-16" ?> 
<A1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <cred xmlns="https://blah-blah.com/?foobar">
        <sub>
            <aa>Zippo</aa> 
            <bb>lighter</bb> 
        </sub>
        <reqId>
            <cc></cc> 
            <dateOfBirth></dateOfBirth> 
        </reqId>
    </cred>
    <reqName xmlns="http://blah-blah/vader/base">qwerty</reqName> 
    <reqId xmlns="http://blah-blah/vader/base">12345</reqId> 
    <machine xmlns="http://blah-blah/vader/base">
        <qqq>hello</qqq> 
        <www>goodbye</www> 
        <eee>99999</eee> 
        <rrr>88888</rrr> 
    </machine>
    <monkey xmlns="http://blah-blah/vader/base">alskdjfhg</monkey> 
    <math xmlns="http://blah-blah/vader/base">
        <language></language> 
    </math>
    <trip xmlns="http://blah-blah/simple">
        <tripOverview xmlns="http://blah-blah/vader/base">
            <description></description> 
            <cost></cost> 
        </tripOverview>
        <bossman xmlns="http://blah-blah/vader/base">
            <zz>CABBAGE</zz> 
            <yy>BANANA</yy> 
            <xx>MELON</xx> 
            <ww>SYRUP</ww> 
        </bossman>
        <items>
            <item>
                <itemSummary xmlns="http://blah-blah/vader/base">
                    <description></description> 
                    <cost></cost> 
                    <reference></reference> 
                </itemSummary>
                <customerInfo xmlns="http://blah-blah/vader/base">
                    <custName></custName> 
                    <custPref>NON-SMOKING</custPref>
                </customerInfo>
                <seatId xmlns="http://blah-blah/vader/base">1</seatId> 
            </item>
        </items>
    </trip>
  </A1>

【问题讨论】:

    标签: c# xml xml-namespaces


    【解决方案1】:
    string xml = "<Root><Options></Options></Root>";
    
    var xdocs = XDocument.Parse(xml);
    
    xdocs.Descendants().Where(q => q.Name == "Options").FirstOrDefault().Value = "FoundIt";
    

    【讨论】:

    • 感谢 Calvin,这对我有很大帮助,我在上面使用了您的代码,但只是添加了 LocalName 属性,即XElement xElement = xDocument.Descendants().Where(q =&gt; q.Name.LocalName == elementName).FirstOrDefault();
    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多