2017-06-17 93 views
0

所以这里是我的XML,并且我明白OrderDate,BuyerID和Items被称为childnodes,但是你怎样调用项目中的属性,如ItemName,Category ect ..他们仍然称为childnodes?如果是的话,他们应该叫什么?XML节点命名

<?xml version="1.0" encoding="utf-8" ?> 
<OrderData > 

    <Order OrderID="OR00001"> 
     <OrderDate>26 May 2017</OrderDate> 
     <BuyerID>WCS1810001</BuyerID> 
     <Instructions>Place item carefully</Instructions> 

     <Items ItemID="IT00001"> 
     <ItemName>ASUS Monitor</ItemName> 
     <Description>Best monitor in the world</Description> 
     <Category>Monitor</Category> 
     <Quantities>100</Quantities> 
     <Manufacturer>ASUS</Manufacturer> 
     <UnitPrice>$100.00</UnitPrice> 
     </Items> 
    </Order> 
</OrderData> 
+0

这取决于你的参考点。物品是Order的孩子。 ItemName是Items的子项,是Order的后代。 – dbasnett

+0

@dbasnett嗯所以可以说,如果我试图处理项目属性,并通常处理子节点会是这样的,order.BuyerID = node.ChildNodes [1] .InnerText; 。 Items属性看起来如何? – randomstudent

+0

项目有一个属性ItemID。这是你指的是什么?我是VB'er,所以我不知道你会如何得到这个属性。处理XML时,IMO VB更容易。 – dbasnett

回答

0

您拥有的唯一属性(xml项)是您的OrderID和ItemID属性。使用xml时,仅使用xml术语很有帮助。因此,你的XML中的所有其他内容都是**元素**。

在另一个元素下的任何元素都是该元素的子元素。

Items是Order的子元素,ItemName是Items的子元素。

+0

他们有OrderID作为订单FWIW的属性。 – dbasnett

0

为什么MS没有添加到C#中超出了我。 VB似乎更适合使用XML恕我直言。

Dim xe As XElement 
    ' to load from a file 
    ' Dim yourpath As String = "your path here" 
    'xe = XElement.Load(yourpath) 

    ' for testing 
    xe = <OrderData> 
      <Order OrderID="OR00001"> 
       <OrderDate>26 May 2017</OrderDate> 
       <BuyerID>WCS1810001</BuyerID> 
       <Instructions>Place item carefully</Instructions> 
       <Items ItemID="IT00001"> 
        <ItemName>ASUS Monitor</ItemName> 
        <Description>Best monitor in the world</Description> 
        <Category>Monitor</Category> 
        <Quantities>100</Quantities> 
        <Manufacturer>ASUS</Manufacturer> 
        <UnitPrice>$100.00</UnitPrice> 
       </Items> 
      </Order> 
     </OrderData> 

    Dim item As XElement 
    'this does not find an item 
    item = (From el In xe...<Items> 
      Where [email protected] = "IT" 
      Select el).FirstOrDefault 

    If item Is Nothing Then Stop 

    'this finds the item 
    item = (From el In xe...<Items> 
      Where [email protected] = "IT00001" 
      Select el).FirstOrDefault 

    'add a new item to the order. an item prototype 
    Dim itmProto As XElement = <Items ItemID=""> 
            <ItemName></ItemName> 
            <Description></Description> 
            <Category></Category> 
            <Quantities></Quantities> 
            <Manufacturer></Manufacturer> 
            <UnitPrice></UnitPrice> 
           </Items> 

    Dim newItem As New XElement(itmProto) 'note that itmProto is not used directly, only as part of New 
    [email protected] = "ITM0042" 
    newItem.<ItemName>.Value = "FOO" 
    newItem.<Description>.Value = "this is a test" 
    'etc 
    xe.<Order>.Last.Add(newItem) 'add to order 

    ' to save file 
    ' xe.Save(yourpath)