【问题标题】:Modify existing XML, adding and deleting nodes java修改现有XML,添加和删除节点java
【发布时间】:2015-08-18 05:23:44
【问题描述】:

现有的 XML

<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2013-08-01">
     <OperationRequest>
           <Arguments>xyz</Arguments>
     </OperationRequest>
     <Items>
        <Item>
            <ItemId>123<ItemId>
            <CustomerReviews>
                  <IFrameURL>someurl</IFrameURL>
                  <HasReviews>true</HasReviews>
            </CustomerReviews>
            <EditorialReviews>
                  <Content>text</Content>
            </EditorialReviews>  
        <Item>
     </Items>

需要转换成

<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2013-08-01">
     <OperationRequest>
           <Arguments>xyz</Arguments>
     </OperationRequest>
     <Items>
        <Item>
            <ItemId>123<ItemId>
            <CustomerReviews>
                  <CustomerReview>
                         <ReviewText>abc<ReviewText>
                         <ReviewDate>May 24, 2015<ReviewDate>
                  </CustomerReview>
                  <CustomerReview>
                         <ReviewText>def<ReviewText>
                         <ReviewDate>June 24, 2014<ReviewDate>
                  </CustomerReview>
                  <HasReviews>true</HasReviews>
            </CustomerReviews>
            <EditorialReviews>
                  <Content>text</Content>
            </EditorialReviews>  
        <Item>
     </Items>

我能够删除 IFrameURL 并能够在 HasReviews 之前插入节点 CustomerReview,但是如何在 CustomerReview 中添加更多节点。 这是我迄今为止使用其他 Stack overflow post 所取得的成就。

<ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2013-08-01">
     <OperationRequest>
           <Arguments>xyz</Arguments>
     </OperationRequest>
     <Items>
        <Item>
            <ItemId>123<ItemId>
            <CustomerReviews>
                  <CustomerReview>hello</CustomerReview>
                  <CustomerReview>hello</CustomerReview>
                  <CustomerReview>hello</CustomerReview>
                  <HasReviews>true</HasReviews>
            </CustomerReviews>
            <EditorialReviews>
                  <Content>text</Content>
            </EditorialReviews>  
        <Item>
     </Items>

PS:XML 结构末尾有 /ItemLookupResponse,但在代码中不可见。

【问题讨论】:

    标签: java xml dom


    【解决方案1】:

    花了一整天的时间,我想通了。

    这里是链接W3Schools,我用来完成工作。细微的区别是,使用 item(index) 函数来访问特定的数组位置。例如使用 DOM java 时,下面代码中的第三行可以替换为x=xmlDoc.getElementsByTagName("book").item(0);

    xmlDoc=loadXMLDoc("books.xml");
    newel=xmlDoc.createElement("edition");
    x=xmlDoc.getElementsByTagName("book")[0];
    x.appendChild(newel);
    

    其他功能也是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多