На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
! Правила раздела Java FAQ
1. Данный раздел предназначен только для публикации готовых статей, с вопросами обращайтесь в соответствующие подразделы.
2. Все вопросы, связанные с ошибками или неточностями в представленных материалах направляйте модераторам персональным сообщением.
3. Все темы и сообщения в разделе премодерируются. Любое сообщение или тема будут доступны остальным участникам после одобрения модераторами.
Модераторы: dark_barker, wind
  
> Создание структуры XML
    ExpandedWrap disabled
      import java.io.File;
       
      import javax.xml.parsers.DocumentBuilder;
      import javax.xml.parsers.DocumentBuilderFactory;
      import javax.xml.parsers.ParserConfigurationException;
      import javax.xml.transform.OutputKeys;
      import javax.xml.transform.Transformer;
      import javax.xml.transform.TransformerException;
      import javax.xml.transform.TransformerFactory;
      import javax.xml.transform.dom.DOMSource;
      import javax.xml.transform.stream.StreamResult;
       
      import org.w3c.dom.Document;
      import org.w3c.dom.Element;
      import org.w3c.dom.Node;
       
      public class DocumentConstructor {
       
          /**
           * Создание XML-документа.
           */
          public static Document constructDocument() throws ParserConfigurationException {
              DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
       
              documentBuilderFactory.setValidating(false);
              documentBuilderFactory.setNamespaceAware(false);
       
              DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
              Document document = documentBuilder.newDocument();
       
              Element root = newElement(document, document, "PresentationInfo", null);
       
              newAttribute(document, root, "Importance", "High");
       
              newElement(document, root, "Author", "Romanov");
              newElement(document, root, "Title", "Захват земли");
              newElement(document, root, "Description", "About marsians taking control over Earth");
              newElement(document, root, "PublicationDate", "10-May-1996");
              newElement(document, root, "Lang", "ru");
              newElement(document, root, "PageCount", "2");
       
              return document;
          }
       
          static Element newElement(Document document, Node parent, String name, String value) {
              Element newElement = document.createElement(name);
       
              if (parent != null) {
                  parent.appendChild(newElement);
              }
       
              if (value != null) {
                  newElement.appendChild(
                      document.createTextNode(value)
                  );
              }
       
              return newElement;
          }
       
          static Attr newAttribute(Document document, Node parent, String name, String value) {
              Attr newAttribute = document.createAttribute(name);
              
              if (parent != null) {
                  parent.getAttributes().setNamedItem(newAttribute);
              }
              
              if (value != null) {
                  newAttribute.setValue(value);
              }
              
              return newAttribute;
          }
       
          /**
           * Сохранение XML-документа в файл.
           */
          public static void saveDocument(Document document, File file) throws TransformerException {
              TransformerFactory transformerFactory = TransformerFactory.newInstance();
              Transformer transformer = transformerFactory.newTransformer();
       
              transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
              transformer.setOutputProperty(OutputKeys.INDENT, "yes");
       
              transformer.transform(
                  new DOMSource(document), new StreamResult(file)
              );
          }
       
      }

    Метод constructDocument() примера создаёт XML-документ со следующей структурой:

    ExpandedWrap disabled
      <PresentationInfo Importance="High">
          <Author>Romanov</Author>
          <Title>Захват земли</Title>
          <Description>About marsians taking control over Earth</Description>
          <PublicationDate>10-May-1996</PublicationDate>
          <Lang>ru</Lang>
          <PageCount>2</PageCount>
      </PresentationInfo>
    0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
    0 пользователей:


    Рейтинг@Mail.ru
    [ Script execution time: 0,0163 ]   [ 15 queries used ]   [ Generated: 28.03.24, 16:36 GMT ]