使用命名空间获取和设置XML元素

问题描述:

新手问题。使用命名空间获取和设置XML元素

我还没有用xml工作过多,不管怎么样。我有一些XML,如下所示,我收到有几个名称空间。

我需要读取一些值,然后更新其他人,然后返回完整的名称空间修订的XML - 不希望他们删除。

我给出这样cred/sub/aatrip/items/item[0]/customerInfo/custName路径的一些元素。

但似乎命名空间很难简单地获取这些元素。

有谁知道我可以从custPref阅读一些像NON-SMOKING值或从bossman/zz获得的价值CABBAGE

而且,我希望能够再设置一个值,如custNameMr. 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> 

string xml = "<Root><Options></Options></Root>"; 

var xdocs = XDocument.Parse(xml); 

xdocs.Descendants().Where(q => q.Name == "Options").FirstOrDefault().Value = "FoundIt"; 
+0

感谢卡尔文,这已经帮助了很多,我用上面的代码,但刚刚添加的属性localName即'的XElement的XElement = xDocument.Descendants()。其中​​(Q => q.Name。 LocalName == elementName).FirstOrDefault();' – user3398094 2014-11-26 11:54:28