2012-12-23 29 views
7

Tôi phải chèn dữ liệu vào một tệp XML ở một nơi cụ thể. Ví dụ:Cách tìm phần tử XML bằng dữ liệu trong đó bằng DOM?

<tag1> 
    <tag2> 
     <tag3>data</tag3> 
    </tag2> 
    <tag2> 
     <tag3>data2</tag3> 
    </tag2> 
</tag1> 

Tôi phải tìm 'data2' sử dụng DOM hơn quay trở lại và chèn các yếu tố mới trong 'TAG2' chứa 'data2' trong đó. Cụ thể hơn, tôi viết một hàm nhận đối số: khóa tìm kiếm và dữ liệu cần chèn.

Tôi làm cách nào để tìm 'data2' và cách quay lại 'tag2' để chèn vào đó?

+0

Bạn có cần định vị bất kỳ thẻ nào có nội dung 'data2' hay bạn cần định vị' thẻ3' thứ hai trong ví dụ, điều này xảy ra có giá trị 'data2'? – Sampson

+0

Giả sử anh ta không hiểu sai câu hỏi, "cách tìm phần tử xml theo dữ liệu trong đó" là hỏi trước, về dữ liệu không phải là thẻ. – jhocking

+0

dữ liệu trong 'tag3' được cho là duy nhất (nhưng không phải ID) và tôi phải tìm phần tử cụ thể với dữ liệu này trong đó – Gesh

Trả lời

0

Sử dụng dữ liệu XML trên của bạn như là một chuỗi:

XMLDocument.prototype.getElementByContent = function getElementByContent(str) { 
    var elems = this.querySelectorAll("*"); 

    for (var i = 0, l = elems.length; i < l; i++) { 
     if (elems[i].textContent === str) { 
     return elems[i]; 
     } 
    } 
}; 

var parser = new DOMParser(); 
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); 

var tag = xmlDoc.createElement("tag3"); 
var content = xmlDoc.createTextNode("data3"); 
tag.appendChild(content); 

xmlDoc.getElementByContent("data2").parentNode.appendChild(tag); 

/* 
    #docment▼ (XMLDocument) 

    <tag1>▼ 
     <tag2>▼ 
      <tag3>data</tag3> 
     </tag2> 
     <tag2>▼ 
      <tag3>data2</tag3> 
      <tag3>data3</tag3> 
     </tag2> 
    </tag1>​ 
*/ 

dụ làm việc: http://jsfiddle.net/elias94xx/nFB7G/

+0

Cảm ơn nó hoạt động nhưng với tôi có một số vấn đề. Tôi đã phải thay đổi mã, để sử dụng ActiveXObject() và một số điều chỉnh khác. Sau đó, nó không làm gì cả. Bất kỳ ý tưởng? Đây là mã: function getElementByContent (str) { var elems = xmlDoc.selectNodes ("// *"); \t var result = new ActiveXObject ("Microsoft.XMLDom"); cho (var i = 0, l = elems.length; i Gesh

+0

Rất tiếc, tôi đã sao chép phiên bản sai chức năng. Đây là bản gốc: function getElementByContent (str) { var elems = xmlDoc.selectNodes ("// *"); \t var result = new ActiveXObject ("Microsoft.XMLDom"); cho (var i = 0, l = elems.length; i Gesh

+0

Tôi hiểu rồi. Tôi không thể gỡ lỗi mã của bạn ngay bây giờ kể từ khi tôi đang trên điện thoại của tôi. Bảng điều khiển javascript có nói gì không? –

0

Ví dụ sau đây cho thấy làm thế nào để sử dụng một số các phương pháp truy cập dữ liệu XML. Đọc các bình luận nội tuyến để hiểu cách mã hoạt động.

Use Notepad or a similar text editor to save the following data as a file named C:\Q317663.xml: 

<?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?> 
<Collection> 
    <Book Id='1' ISBN='1-100000ABC-200'> 
     <Title>Principle of Relativity</Title> 
     <!-- Famous physicist -->  
     <Author>Albert Einstein</Author> 
     <Genre>Physics</Genre> 
    </Book> 
    <Book Id='2' ISBN='1-100000ABC-300'> 
     <!-- Also came as a TV serial --> 
     <Title>Cosmos</Title> 
     <Author>Carl Sagan</Author> 
     <Genre>Cosmology</Genre> 
    </Book> 
    <!-- Add additional books here --> 
</Collection> 


Create a new Visual Basic .NET Console Application project. 
Replace the code in Module1.vb with the following code. This example loads the XML document from a file representing a collection of Books and then accesses the content using some of the methods mentioned earlier. 

Imports System.Xml 
Imports System.Text 

Module Module1 

    Sub Main() 

     Try 

     ' Create an Xml document instance and load XML data. 
     Dim doc As XmlDocument = New XmlDocument() 
     doc.Load("C:\Q317663.xml")      

     ' 1. Select all the Book titles by using an XPath query. 
     Dim nodeList As XmlNodeList = doc.SelectNodes("//Book/Title") 
     Dim node As XmlNode 
     Console.WriteLine("{0}", "TITLES LIST: ") 
     For Each node In nodeList 
      Console.WriteLine("{0}", node.InnerText) 
     Next 

     ' 2. Read the XmlDeclartion values. 
     Dim decl As XmlDeclaration = CType(doc.FirstChild, XmlDeclaration) 
     Console.WriteLine("{0}", vbNewLine & "XML DECLARTION:") 
     Console.WriteLine("{0}", "Version " & "= " & decl.Version) 
     Console.WriteLine("{0}", "Encoding " & "= " & decl.Encoding) 
     Console.WriteLine("{0}", "Standalone " & "= " & decl.Standalone) 

     ' 3. Move to the first node of DOM and get all of its attributes. 
     Dim root As XmlElement = doc.DocumentElement 
     node = root.FirstChild 
     Dim attr As XmlAttribute 
     Console.WriteLine("{0}", vbNewLine & "ATTRIBUTES OF THE FIRST CHILD:") 
     For Each attr In node.Attributes 
      Console.WriteLine("{0}", attr.Name & " = " & attr.InnerText) 
     Next 

     ' 4. Navigate to the child nodes of the first Book node. 
     Dim cNode As XmlNode 
     Console.WriteLine("{0}", vbNewLine & "FIRST NODE'S CHILDREN:") 
     If node.HasChildNodes Then 
      For Each cNode In node.ChildNodes 
       Console.WriteLine("{0}", cNode.OuterXml) 
      Next 
     End If 

     ' 5. Navigate to the next sibling of the first Book node. 
     node = node.NextSibling 
     Console.WriteLine("{0}", vbNewLine & "NEXT SIBLING:") 
     If Not node Is Nothing Then 
      Console.WriteLine("{0}", node.OuterXml) 
     End If 

     ' 6. Get the parent node details of the current node. 
     Console.WriteLine("{0}", vbNewLine & "PARENT NODE NAME = " & node.ParentNode.Name) 
     Console.WriteLine("{0}", "PARENT NODE HAS " & node.ParentNode.ChildNodes.Count & " CHILD NODES") 
     Console.WriteLine("{0}", "PARENT NODE'S NAMESPACE URI = " & node.ParentNode.NamespaceURI) 

     ' 7. Count the number of Comment nodes in the document. 
     ' You could search for other types in the same way. 
     Dim commentNodes As Integer = GetNodeTypeCount(doc.DocumentElement, XmlNodeType.Comment) 
     Console.WriteLine("{0}", vbNewLine & "NUMBER OF COMMENT NODES IN THE DOC = " & commentNodes & vbNewLine) 

      Console.ReadLine() 

     Catch xmlex As XmlException     ' Handle the Xml Exceptions here 
     Console.WriteLine("{0}", xmlex.Message) 
     Catch ex As Exception      ' Handle the generic Exceptions here 
     Console.WriteLine("{0}", ex.Message) 
     End Try 

    End Sub 

    Function GetNodeTypeCount(ByVal node As XmlNode, ByVal nodeType As XmlNodeType) As Integer 

     ' Recursively loop through the given node and return 
     ' the number of occurences of a specific nodeType. 
     Dim i As Integer = 0 
     Dim cNode As XmlNode 
     If node.NodeType = nodeType Then 
     i = i + 1 
     End If 
     If node.HasChildNodes Then 
     For Each cNode In node.ChildNodes 
      i = i + GetNodeTypeCount(cNode, nodeType) 
     Next 
     End If 
     GetNodeTypeCount = i 

    End Function 

End Module 


Compile and then run the application. The output should resemble the following: 

TITLES LIST: 
Principle of Relativity 
Cosmos 

XML DECLARTION: 
Version = 1.0 
Encoding = ISO-8859-1 
Standalone = yes 

ATTRIBUTES OF THE FIRST CHILD: 
Id = 1 
ISBN = 1-100000ABC-200 

FIRST NODE'S CHILDREN: 
<Title>Principle of Relativity</Title> 
<!-- Famous physicist --> 
<Author>Albert Einstein</Author> 
<Genre>Physics</Genre> 

NEXT SIBLING: 
<Book Id="2" ISBN="1-100000ABC-300"><!-- Also came as a TV serial --><Title>Cosm 
os</Title><Author>Carl Sagan</Author><Genre>Cosmology</Genre></Book> 

PARENT NODE NAME = Collection 
PARENT NODE HAS 3 CHILD NODES 
PARENT NODE'S NAMESPACE URI = 

NUMBER OF COMMENT NODES IN THE DOC = 3 
Các vấn đề liên quan