Beispiel #1
0
 /** 解析xml元素 */
 @Override
 public void startElement(String uri, String localName, String qName, Attributes attributes)
     throws SAXException {
   // 调用DefaultHandler类的startElement方法
   super.startElement(uri, localName, qName, attributes);
   if (qName.equals("book")) {
     bookIndex++;
     // 创建一个book对象
     book = new Book();
     // 开始解析book元素的属性
     System.out.println("======================开始遍历某一本书的内容=================");
     // //已知book元素下属性的名称,根据属性名称获取属性值
     // String value = attributes.getValue("id");
     // System.out.println("book的属性值是:" + value);
     // 不知道book元素下属性的名称以及个数,如何获取属性名以及属性值
     int num = attributes.getLength();
     for (int i = 0; i < num; i++) {
       System.out.print("book元素的第" + (i + 1) + "个属性名是:" + attributes.getQName(i));
       System.out.println("---属性值是:" + attributes.getValue(i));
       if (attributes.getQName(i).equals("id")) {
         book.setId(attributes.getValue(i));
       }
     }
   } else if (!qName.equals("name") && !qName.equals("bookstore")) {
     System.out.print("节点名是:" + qName + "---");
   }
 }
 @Override
 public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
     throws SAXException {
   if ("message".equals(qName)) {
     entry = new EntryImpl();
     for (int i = 0; i < atts.getLength(); i++) {
       if ("time".equals(atts.getQName(i))) {
         try {
           entry.setTime(EmpathyParser.TIME_FORMAT.parse(atts.getValue(i)));
         } catch (ParseException ex) {
           LOG.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
         }
       }
       if ("name".equals(atts.getQName(i))) {
         entry.setName(atts.getValue(i));
       }
       if ("type".equals(atts.getQName(i))) {
         entry.setType(atts.getValue(i));
       }
       if ("id".equals(atts.getQName(i))) {
         entry.setId(atts.getValue(i));
       }
     }
   }
 }
Beispiel #3
0
  public static String saxElementToDebugString(String uri, String qName, Attributes attributes) {
    // Open start tag
    final StringBuilder sb = new StringBuilder("<");
    sb.append(qName);

    final Set<String> declaredPrefixes = new HashSet<String>();
    mapPrefixIfNeeded(declaredPrefixes, uri, qName, sb);

    // Attributes if any
    for (int i = 0; i < attributes.getLength(); i++) {
      mapPrefixIfNeeded(declaredPrefixes, attributes.getURI(i), attributes.getQName(i), sb);

      sb.append(' ');
      sb.append(attributes.getQName(i));
      sb.append("=\"");
      sb.append(attributes.getValue(i));
      sb.append('\"');
    }

    // Close start tag
    sb.append('>');

    // Content
    sb.append("[...]");

    // Close element with end tag
    sb.append("</");
    sb.append(qName);
    sb.append('>');

    return sb.toString();
  }
    /*
     * Appends the page directive with the given attributes to the XML
     * view.
     *
     * Since the import attribute of the page directive is the only page
     * attribute that is allowed to appear multiple times within the same
     * document, and since XML allows only single-value attributes,
     * the values of multiple import attributes must be combined into one,
     * separated by comma.
     *
     * If the given page directive contains just 'contentType' and/or
     * 'pageEncoding' attributes, we ignore it, as we've already appended
     * a page directive containing just these two attributes.
     */
    private void appendPageDirective(Node.PageDirective n) {
      boolean append = false;
      Attributes attrs = n.getAttributes();
      int len = (attrs == null) ? 0 : attrs.getLength();
      for (int i = 0; i < len; i++) {
        @SuppressWarnings("null") // If attrs==null, len == 0
        String attrName = attrs.getQName(i);
        if (!"pageEncoding".equals(attrName) && !"contentType".equals(attrName)) {
          append = true;
          break;
        }
      }
      if (!append) {
        return;
      }

      buf.append("<").append(n.getQName());
      buf.append("\n");

      // append jsp:id
      buf.append("  ").append(jspIdPrefix).append(":id").append("=\"");
      buf.append(jspId++).append("\"\n");

      // append remaining attributes
      for (int i = 0; i < len; i++) {
        @SuppressWarnings("null") // If attrs==null, len == 0
        String attrName = attrs.getQName(i);
        if ("import".equals(attrName)
            || "contentType".equals(attrName)
            || "pageEncoding".equals(attrName)) {
          /*
           * Page directive's 'import' attribute is considered
           * further down, and its 'pageEncoding' and 'contentType'
           * attributes are ignored, since we've already appended
           * a new page directive containing just these two
           * attributes
           */
          continue;
        }
        String value = attrs.getValue(i);
        buf.append("  ").append(attrName).append("=\"");
        buf.append(JspUtil.getExprInXml(value)).append("\"\n");
      }
      if (n.getImports().size() > 0) {
        // Concatenate names of imported classes/packages
        boolean first = true;
        ListIterator<String> iter = n.getImports().listIterator();
        while (iter.hasNext()) {
          if (first) {
            first = false;
            buf.append("  import=\"");
          } else {
            buf.append(",");
          }
          buf.append(JspUtil.getExprInXml(iter.next()));
        }
        buf.append("\"\n");
      }
      buf.append("/>\n");
    }
 @Override
 public void setAttributes(final Attributes atts) {
   for (int i = 0; i < atts.getLength(); i++) {
     if (!qNames.add(atts.getQName(i))) {
       handleDuplicate(atts.getQName(i), atts.getValue(i));
     }
   }
   super.setAttributes(atts);
 }
 /**
  * Write start element.
  *
  * @param elemName element name
  * @param atts attribute
  * @param removeConref whether remeove conref info
  * @throws SAXException if writing element failed
  */
 private void putElement(final String elemName, final Attributes atts, final boolean removeConref)
     throws SAXException {
   // parameter boolean removeConref specifies whether to remove
   // conref information like @conref @conaction in current element
   // when copying it to pushcontent. True means remove and false means
   // not remove.
   try {
     pushcontentWriter.writeStartElement(elemName);
     for (int index = 0; index < atts.getLength(); index++) {
       final String name = atts.getQName(index);
       if (!removeConref
           || !ATTRIBUTE_NAME_CONREF.equals(name) && !ATTRIBUTE_NAME_CONACTION.equals(name)) {
         String value = atts.getValue(index);
         if (ATTRIBUTE_NAME_HREF.equals(name) || ATTRIBUTE_NAME_CONREF.equals(name)) {
           // adjust href for pushbefore and replace
           value = replaceURL(value);
         }
         final int offset = atts.getQName(index).indexOf(":");
         final String prefix = offset != -1 ? atts.getQName(index).substring(0, offset) : "";
         pushcontentWriter.writeAttribute(
             prefix, atts.getURI(index), atts.getLocalName(index), value);
       }
     }
     // id attribute should only be added to the starting element
     // which dosen't have id attribute set
     if (ATTR_CONACTION_VALUE_PUSHREPLACE.equals(pushType)
         && atts.getValue(ATTRIBUTE_NAME_ID) == null
         && level == 1) {
       final String fragment = target.getFragment();
       if (fragment == null) {
         // if there is no '#' in target string, report error
         logger.error(
             MessageUtils.getInstance().getMessage("DOTJ041E", target.toString()).toString());
       } else {
         String id = "";
         // has element id
         if (fragment.contains(SLASH)) {
           id = fragment.substring(fragment.lastIndexOf(SLASH) + 1);
         } else {
           id = fragment;
         }
         // add id attribute
         pushcontentWriter.writeAttribute(ATTRIBUTE_NAME_ID, id);
       }
     }
   } catch (final XMLStreamException e) {
     throw new SAXException(e);
   }
 }
  @Override
  public void startElement(String uri, String localName, String name, Attributes attributes)
      throws SAXException {

    if (this.start) {
      if (uri != null) {
        int numAtts = attributes.getLength();

        for (int i = 0; i < numAtts; i++) {
          String attQName = attributes.getQName(i);

          if (attQName.equals("xmlns") || attQName.startsWith("xmlns:")) {
            String attValue = attributes.getValue(i);

            if (uri.equals(attValue)) {
              this.nsSpec = attValue;
              break;
            }
          }
        }
      }

      this.start = false;
    }

    super.startElement(uri, localName, name, attributes);
  }
  /**
   * Processes ?include directive
   *
   * @param include
   */
  @NbBundle.Messages({
    "ERR_missingIncludeName=Missing include name",
    "# {0} - attribute name",
    "ERR_unexpectedIncludeAttribute=Unexpected attribute in fx:include: {0}"
  })
  private FxNode handleFxInclude(Attributes atts, String localName) {
    String include = null;

    for (int i = 0; i < atts.getLength(); i++) {
      String attName = atts.getLocalName(i);
      if (FX_ATTR_REFERENCE_SOURCE.equals(attName)) {
        include = atts.getValue(i);
      } else {
        String qName = atts.getQName(i);
        addAttributeError(
            qName, "unexpected-include-attribute", ERR_unexpectedIncludeAttribute(qName), qName);
      }
    }
    if (include == null) {
      // must be some text, otherwise = error
      addAttributeError(
          ContentLocator.ATTRIBUTE_TARGET, "missing-included-name", ERR_missingIncludeName());

      FxNode n = accessor.createErrorElement(localName);
      initElement(n);
      addError("invalid-fx-element", ERR_invalidFxElement(localName), localName);
      return n;
    }
    // guide: fnames starting with slash are treated relative to the classpath
    FxInclude fxInclude = accessor.createInclude(include);
    return fxInclude;
  }
 /**
  * Set all personal properties of an XML file for an item (doesn't overwrite existing properties
  * for perfs).
  *
  * @param attributes : list of attributes for this XML item
  */
 @Override
 public void populateProperties(final Attributes attributes) {
   for (int i = 0; i < attributes.getLength(); i++) {
     final String sProperty = attributes.getQName(i);
     if (!getProperties().containsKey(sProperty)) {
       String sValue = attributes.getValue(i);
       final PropertyMetaInformation meta = getMeta(sProperty);
       // compatibility code for <1.1 : auto-refresh is now a double,
       // no more a boolean
       if (meta.getName().equals(Const.XML_DEVICE_AUTO_REFRESH)
           && (sValue.equalsIgnoreCase(Const.TRUE) || sValue.equalsIgnoreCase(Const.FALSE))) {
         if (getType() == Type.DIRECTORY) {
           sValue = "0.5d";
         }
         if (getType() == Type.FILES_CD) {
           sValue = "0d";
         }
         if (getType() == Type.NETWORK_DRIVE) {
           sValue = "0d";
         }
         if (getType() == Type.EXTDD) {
           sValue = "3d";
         }
         if (getType() == Type.PLAYER) {
           sValue = "3d";
         }
       }
       try {
         setProperty(sProperty, UtilString.parse(sValue, meta.getType()));
       } catch (final Exception e) {
         Log.error(137, sProperty, e);
       }
     }
   }
 }
Beispiel #10
0
  public void startElement(String namespaceURI, String sName, String qName, Attributes attrs)
      throws SAXException {

    echoText();

    String eName = sName; // element name
    if ("".equals(eName)) {
      eName = qName; // not namespace-aware
    }

    if ("HTTPSamplerProxy".equals(eName)) {
      startBuffer();
    }

    emit("<" + eName);
    if (attrs != null) {
      for (int i = 0; i < attrs.getLength(); i++) {
        String aName = attrs.getLocalName(i); // Attr name
        if ("".equals(aName)) aName = attrs.getQName(i);

        emit(" ");
        if ("HTTPSamplerProxy".equals(eName) && "testname".equals(aName)) {
          this.testName = attrs.getValue(i);
        }
        emit(aName + "=\"" + attrs.getValue(i) + "\"");
      }
    }

    emit(">");
  }
Beispiel #11
0
  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes)
      throws SAXException {
    ModelReader8Handler.ElementHandler current =
        (myHandlersStack.empty()
            ? (ModelReader8Handler.ElementHandler) null
            : myHandlersStack.peek());
    if (current == null) {
      // root
      current = modelhandler;
    } else {
      current = current.createChild(myValues.peek(), qName, attributes);
    }

    // check required
    for (String attr : current.requiredAttributes()) {
      if (attributes.getValue(attr) == null) {
        throw new SAXParseException("attribute " + attr + " is absent", null);
      }
    }

    Object result = current.createObject(attributes);
    if (myHandlersStack.empty()) {
      myResult = (ModelLoadResult) result;
    }

    // handle attributes
    for (int i = 0; i < attributes.getLength(); i++) {
      String name = attributes.getQName(i);
      String value = attributes.getValue(i);
      current.handleAttribute(result, name, value);
    }
    myHandlersStack.push(current);
    myValues.push(result);
  }
    /* (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
      super.startElement(uri, localName, qName, attributes);
      for (DefaultHandler delegate : delegates) {
        delegate.startElement(uri, localName, qName, attributes);
      }
      boolean policy = false;
      if (localName != null && localName.equals(POLICY)) {
        policy = true;
      }
      if (qName != null && qName.endsWith(COLON_POLICY)) {
        policy = true;
      }
      if (!policy) {
        return;
      } else {
        hasPolicy = true;
      }
      int count = attributes.getLength();
      for (int i = 0; i < count; i++) {
        String value = attributes.getValue(i);
        String attrLocalName = attributes.getLocalName(i);
        String attrQName = attributes.getQName(i);

        if ((attrLocalName != null && attrLocalName.equals(ID))
            || (attrLocalName != null && attrQName.endsWith(COLON_ID))) {
          policies.add(attributes.getValue(i));
        }
      }
    }
 public void startElement(String namespaceURI, String localName, String qName, Attributes attr) {
   String prefix = "";
   if (qName.lastIndexOf(":") != -1) prefix = qName.substring(0, qName.lastIndexOf(":"));
   String attrPrefix, attrQName;
   Attribute att;
   // if root element is null, then this first element will be the root element
   Element elem = new Element(localName, prefix, namespaceURI);
   for (int i = 0; i < attr.getLength(); i++) {
     attrQName = attr.getQName(i);
     if (attrQName.lastIndexOf(":") != -1)
       attrPrefix = attrQName.substring(0, attrQName.lastIndexOf(":"));
     else attrPrefix = "";
     att =
         new Attribute(
             attr.getLocalName(i),
             attr.getValue(i),
             Namespace.getNamespace(attrPrefix, attr.getURI(i)));
     elem.setAttribute(att);
   }
   if (rootElem == null) {
     rootElem = elem;
     curElem = rootElem;
   } else {
     curElem.addContent(elem);
     // set to the next element
     curElem = elem;
   }
 }
  /** Appends a start tag to charBuf. This method is used during the parsing of an XML Literal. */
  private void appendStartTag(String qName, Attributes attributes) {
    // Write start of start tag
    charBuf.append("<" + qName);

    // Write any new namespace prefix definitions
    for (Map.Entry<String, String> entry : newNamespaceMappings.entrySet()) {
      String prefix = entry.getKey();
      String namespace = entry.getValue();
      appendNamespaceDecl(charBuf, prefix, namespace);
    }

    // Write attributes
    int attCount = attributes.getLength();
    for (int i = 0; i < attCount; i++) {
      appendAttribute(charBuf, attributes.getQName(i), attributes.getValue(i));
    }

    // Write end of start tag
    charBuf.append(">");

    // Check for any used prefixes that are not
    // defined in the XML literal itself
    int colonIdx = qName.indexOf(':');
    String prefix = (colonIdx > 0) ? qName.substring(0, colonIdx) : "";

    if (!xmlLiteralPrefixes.contains(prefix) && !unknownPrefixesInXMLLiteral.contains(prefix)) {
      unknownPrefixesInXMLLiteral.add(prefix);
    }
  }
 private void processAttributes(final Attributes atts) {
   // Check the root for model annotation information
   for (int i = 0; i < atts.getLength(); i++) {
     final String name = atts.getLocalName(i);
     final String value = atts.getValue(i);
     final String qname = atts.getQName(i);
     // The UUID associated with the model is the ModelAnnotation UUID
     // unless this is a VDB in which case it is the VirtualDatabase UUID
     if (name.equalsIgnoreCase(UUID_ATTRIBUTE_NAME) && !this.foundVdbStartElement)
       this.getXmiHeader().setUUID(value);
     else if (name.equalsIgnoreCase(DESCRIPTION_ATTRIBUTE_NAME))
       this.getXmiHeader().setDescription(value);
     else if (name.equalsIgnoreCase(PRODUCER_NAME_ATTRIBUTE_NAME))
       this.getXmiHeader().setProducerName(value);
     else if (name.equalsIgnoreCase(PRODUCER_VERSION_ATTRIBUTE_NAME))
       this.getXmiHeader().setProducerVersion(value);
     else if (name.equalsIgnoreCase(PRIMARY_URI_ATTRIBUTE_NAME))
       this.getXmiHeader().setPrimaryMetamodelURI(value);
     else if (name.equalsIgnoreCase(MODEL_TYPE_ATTRIBUTE_NAME))
       this.getXmiHeader().setModelType(value);
     else if (name.equalsIgnoreCase(MODEL_NAMESPACE_URI))
       this.getXmiHeader().setModelNamespaceUri(value);
     else if (name.equalsIgnoreCase(VISIBLE_ATTRIBUTE_NAME)) this.getXmiHeader().setVisible(value);
     else if (qname.equalsIgnoreCase(XMI_VERSION_0020_ATTRIBUTE_NAME))
       this.getXmiHeader().setXmiVersion(value);
     else if (qname.equalsIgnoreCase(XMI_VERSION_0011_ATTRIBUTE_NAME))
       this.getXmiHeader().setXmiVersion(value);
   }
 }
  public void startElement(String namespaceURI, String lName, String qName, Attributes attrs)
      throws SAXException {
    String eName = lName;
    if ("".equals(eName)) // $NON-NLS-1$
    eName = qName;

    // Important to clear buffer :)
    chars = ""; // $NON-NLS-1$

    if (eName.equals("provider")) { // $NON-NLS-1$
      providerName = ""; // $NON-NLS-1$
      phoneNumber = ""; // $NON-NLS-1$
      providerID = 0; // $NON-NLS-1$
      active = false;
    }
    if (attrs != null) {
      for (int i = 0; i < attrs.getLength(); i++) {
        String aName = attrs.getLocalName(i); // Attr name
        if ("".equals(aName)) // $NON-NLS-1$
        aName = attrs.getQName(i);
        if (eName.equals("entry") && aName.equals("id")) { // $NON-NLS-1$,  //$NON-NLS-2$
          providerID = Integer.parseInt(attrs.getValue(i));
        }
      }
    }
  }
  /**
   * Handle the beginning of an XML element.
   *
   * @param attributes The attributes of this element
   * @exception Exception if a processing error occurs
   */
  public void begin(String namespace, String nameX, Attributes attributes) throws Exception {

    for (int i = 0; i < attributes.getLength(); i++) {
      String name = attributes.getLocalName(i);
      if ("".equals(name)) {
        name = attributes.getQName(i);
      }
      if ("path".equals(name) || "docBase".equals(name)) {
        continue;
      }
      String value = attributes.getValue(i);
      if (!digester.isFakeAttribute(digester.peek(), name)
          && !IntrospectionUtils.setProperty(digester.peek(), name, value)
          && digester.getRulesValidation()) {
        digester
            .getLogger()
            .warn(
                "[SetContextPropertiesRule]{"
                    + digester.getMatch()
                    + "} Setting property '"
                    + name
                    + "' to '"
                    + value
                    + "' did not find a matching property.");
      }
    }
  }
Beispiel #18
0
  public void startElement(
      String namespaceURI,
      String localName, // local name
      String qName, // qualified name
      Attributes attrs)
      throws SAXException {
    echoTextBuffer();

    // Namen eines Elementes herausfinden
    String eName = ("".equals(localName)) ? qName : localName;
    echoString("*Anfang Element mit Namen " + eName + "*:");
    // echoString( "<" + eName );

    // Feld mit Attributen durchgehen// element name
    if (attrs != null) {
      for (int i = 0; i < attrs.getLength(); i++) {
        // Name eines Attributs
        String aName = attrs.getLocalName(i); // Attr name
        // 2. Versuch
        if ("".equals(aName)) aName = attrs.getQName(i);
        // Ausgabe des Attributs
        echoString("\n    + Neues Attribut mit Name/Wert: " + aName + "/" + attrs.getValue(i));
      }
    }
    // echoString( ">" );
  }
  public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
      throws SAXException {
    try {
      if (qName.equals("nite:root")) {
        labeledResult = new ArrayList<String>();
      } else if (qName.equals("word")) {
        int length = atts.getLength();

        // Process each attribute
        for (int i = 0; i < length; i++) {
          // Get names and values for each attribute
          String name = atts.getQName(i);
          String value = atts.getValue(i);

          if ((name != null) && (value != null)) {
            if (name.equals("nite:id")) {
              localID = value;
            }
          }
        }
      }
    } catch (Exception e) {
      //		    e.printStackTrace();
      throw new GrobidException("An exception occured while running Grobid.", e);
    }
  }
Beispiel #20
0
  @Test
  public void testAttributesBuilder() throws ParserConfigurationException {
    final XMLUtils.AttributesBuilder b = new XMLUtils.AttributesBuilder();
    assertEquals(0, b.build().getLength());

    b.add("foo", "bar");
    b.add("uri", "foo", "prefix:foo", "CDATA", "qux");
    final Attributes a = b.build();
    assertEquals("bar", a.getValue("foo"));
    assertEquals("qux", a.getValue("prefix:foo"));
    assertEquals(2, a.getLength());
    for (int i = 0; i < a.getLength(); i++) {
      if (a.getQName(i).equals("prefix:foo")) {
        assertEquals("uri", a.getURI(i));
        assertEquals("foo", a.getLocalName(i));
        assertEquals("prefix:foo", a.getQName(i));
        assertEquals("CDATA", a.getType(i));
        assertEquals("qux", a.getValue(i));
      }
    }

    b.add("foo", "quxx");
    final Attributes aa = b.build();
    assertEquals("quxx", aa.getValue("foo"));
    assertEquals(2, aa.getLength());

    final AttributesImpl ai = new AttributesImpl();
    ai.addAttribute(NULL_NS_URI, "baz", "baz", "CDATA", "all");
    b.addAll(ai);
    final Attributes aaa = b.build();
    assertEquals("all", aaa.getValue("baz"));
    assertEquals(3, aaa.getLength());

    final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    final Attr domAttr = doc.createAttributeNS(XML_NS_URI, "xml:space");
    domAttr.setValue("preserve");
    b.add(domAttr);
    final Attributes a4 = b.build();
    for (int i = 0; i < a4.getLength(); i++) {
      if (a4.getQName(i).equals("xml:space")) {
        assertEquals(XML_NS_URI, a4.getURI(i));
        assertEquals("space", a4.getLocalName(i));
        assertEquals("xml:space", a4.getQName(i));
        assertEquals("preserve", a4.getValue(i));
      }
    }
  }
  public void pushAttributes(Attributes atts, boolean collectTextFlag) {

    if (attStack.length == elementDepth) {
      // reallocate the buffer
      AttributesImpl[] buf1 = new AttributesImpl[attStack.length * 2];
      System.arraycopy(attStack, 0, buf1, 0, attStack.length);
      attStack = buf1;

      int[] buf2 = new int[idxStack.length * 2];
      System.arraycopy(idxStack, 0, buf2, 0, idxStack.length);
      idxStack = buf2;

      boolean[] buf3 = new boolean[collectText.length * 2];
      System.arraycopy(collectText, 0, buf3, 0, collectText.length);
      collectText = buf3;
    }

    elementDepth++;
    stackTop++;

    // push the stack
    AttributesImpl a = attStack[stackTop];
    if (a == null) attStack[stackTop] = a = new AttributesImpl();
    else a.clear();

    // since Attributes object is mutable, it is criticall important
    // to make a copy.
    // also symbolize attribute names
    for (int i = 0; i < atts.getLength(); i++) {
      String auri = atts.getURI(i);
      String alocal = atts.getLocalName(i);
      String avalue = atts.getValue(i);
      String aqname = atts.getQName(i);

      // work gracefully with misconfigured parsers that don't support namespaces
      if (auri == null) auri = "";
      if (alocal == null || alocal.length() == 0) alocal = aqname;
      if (aqname == null || aqname.length() == 0) aqname = alocal;

      // <foo xsi:nil="false">some value</foo> is a valid fragment, however
      // we need a look ahead to correctly handle this case.
      // (because when we process @xsi:nil, we don't know what the value is,
      // and by the time we read "false", we can't cancel this attribute anymore.)
      //
      // as a quick workaround, we remove @xsi:nil if the value is false.
      if (auri == "http://www.w3.org/2001/XMLSchema-instance" && alocal == "nil") {
        String v = avalue.trim();
        if (v.equals("false") || v.equals("0")) continue; // skip this attribute
      }

      // otherwise just add it.
      a.addAttribute(auri, alocal, aqname, atts.getType(i), avalue);
    }

    // start a new namespace scope
    idxStack[stackTop] = nsLen;

    collectText[stackTop] = collectTextFlag;
  }
Beispiel #22
0
 public void startElement(String nm, String ln, String qn, Attributes as) throws SAXException {
   if (level++ == 0)
     for (int i = 0; i < as.getLength(); i++)
       if (attributename.equals("*") || attributename.equals(as.getQName(i))) {
         char[] s = as.getValue(i).toCharArray();
         next.characters(s, 0, s.length);
       }
 }
Beispiel #23
0
    public void startElement(String ur, String localName, String qName, Attributes attributes) {
      currentQName = qName;

      if (qName.indexOf("BinData") == -1) {
        xmlBuffer.append("<");
        xmlBuffer.append(qName);
        for (int i = 0; i < attributes.getLength(); i++) {
          String key = XMLTools.escapeXML(attributes.getQName(i));
          String value = XMLTools.escapeXML(attributes.getValue(i));
          if (key.equals("BigEndian")) {
            String endian = value.toLowerCase();
            if (!endian.equals("true") && !endian.equals("false")) {
              // hack for files that specify 't' or 'f' instead of
              // 'true' or 'false'
              if (endian.startsWith("t")) endian = "true";
              else if (endian.startsWith("f")) endian = "false";
            }
            value = endian;
          }
          xmlBuffer.append(" ");
          xmlBuffer.append(key);
          xmlBuffer.append("=\"");
          xmlBuffer.append(value);
          xmlBuffer.append("\"");
        }
        xmlBuffer.append(">");
      } else {
        binData.add(new BinData(locator.getLineNumber(), locator.getColumnNumber()));
        String compress = attributes.getValue("Compression");
        compression.add(compress == null ? "" : compress);

        xmlBuffer.append("<");
        xmlBuffer.append(qName);
        for (int i = 0; i < attributes.getLength(); i++) {
          String key = XMLTools.escapeXML(attributes.getQName(i));
          String value = XMLTools.escapeXML(attributes.getValue(i));
          if (key.equals("Length")) value = "0";
          xmlBuffer.append(" ");
          xmlBuffer.append(key);
          xmlBuffer.append("=\"");
          xmlBuffer.append(value);
          xmlBuffer.append("\"");
        }
        xmlBuffer.append(">");
      }
    }
  @NbBundle.Messages({
    "# {0} - attribute local name",
    "ERR_unexpectedReferenceAttribute=Unexpected attribute in fx:reference or fx:copy: {0}",
    "ERR_missingReferenceSource=Missing 'source' attribute in fx:reference or fx:copy"
  })
  private FxNode handleFxReference(Attributes atts, boolean copy) {
    String refId = null;
    String id = null;

    for (int i = 0; i < atts.getLength(); i++) {
      String ns = atts.getURI(i);
      String name = atts.getLocalName(i);
      if (!FXML_FX_NAMESPACE.equals(ns)) {
        if (FX_ATTR_REFERENCE_SOURCE.equals(name) && refId == null) {
          refId = atts.getValue(i);
        } else if (!copy) {
          // error, references do not support normal attributes
          addAttributeError(
              atts.getQName(i),
              "invalid-reference-attribute",
              ERR_unexpectedReferenceAttribute(name),
              name);
        }
      } else {
        if (FX_ID.equals(name) && id == null) {
          id = atts.getValue(i);
        } else {
          // error, unexpected attribute
          addAttributeError(
              atts.getQName(i),
              "invalid-reference-attribute",
              ERR_unexpectedReferenceAttribute(name),
              name);
        }
      }
    }

    FxObjectBase ref = accessor.createCopyReference(copy, refId);
    if (refId == null || "".equals(refId)) {
      // error, no source attribute found
      addError("missing-reference-source", ERR_missingReferenceSource());
      accessor.makeBroken(ref);
    }
    return ref;
  }
    /*
     * Appends the attributes of the given Node to the XML view.
     */
    private void printAttributes(Node n, boolean addDefaultNS) {

      /*
       * Append "xmlns" attributes that represent tag libraries
       */
      Attributes attrs = n.getTaglibAttributes();
      int len = (attrs == null) ? 0 : attrs.getLength();
      for (int i = 0; i < len; i++) {
        @SuppressWarnings("null") // If attrs==null, len == 0
        String name = attrs.getQName(i);
        String value = attrs.getValue(i);
        buf.append("  ").append(name).append("=\"").append(value).append("\"\n");
      }

      /*
       * Append "xmlns" attributes that do not represent tag libraries
       */
      attrs = n.getNonTaglibXmlnsAttributes();
      len = (attrs == null) ? 0 : attrs.getLength();
      boolean defaultNSSeen = false;
      for (int i = 0; i < len; i++) {
        @SuppressWarnings("null") // If attrs==null, len == 0
        String name = attrs.getQName(i);
        String value = attrs.getValue(i);
        buf.append("  ").append(name).append("=\"").append(value).append("\"\n");
        defaultNSSeen |= "xmlns".equals(name);
      }
      if (addDefaultNS && !defaultNSSeen) {
        buf.append("  xmlns=\"\"\n");
      }
      resetDefaultNS = false;

      /*
       * Append all other attributes
       */
      attrs = n.getAttributes();
      len = (attrs == null) ? 0 : attrs.getLength();
      for (int i = 0; i < len; i++) {
        @SuppressWarnings("null") // If attrs==null, len == 0
        String name = attrs.getQName(i);
        String value = attrs.getValue(i);
        buf.append("  ").append(name).append("=\"");
        buf.append(JspUtil.getExprInXml(value)).append("\"\n");
      }
    }
Beispiel #26
0
 @Override
 public void startElement(String uri, String localName, String qName, Attributes attributes)
     throws SAXException {
   System.out.print("<" + qName);
   for (int i = 0; i < attributes.getLength(); i++)
     System.out.format(" %s='%s'", attributes.getQName(i), attributes.getValue(i));
   System.out.print(">");
   super.startElement(uri, localName, qName, attributes);
 }
 @Override
 public void startElement(String uri, String localName, String qName, Attributes attributes)
     throws SAXException {
   AnnotationData data = new AnnotationData(qName, regionInfo);
   for (int i = 0; i < attributes.getLength(); i++) {
     data.addAttr(attributes.getQName(i), attributes.getValue(i));
   }
   SourceAnnotationReader.this.fAnnotations.add(data);
 }
Beispiel #28
0
 protected void writeAttribute(Attributes attributes, int index) throws IOException {
   char quote = format.getAttributeQuoteCharacter();
   writer.write(" ");
   writer.write(attributes.getQName(index));
   writer.write("=");
   writer.write(quote);
   writeEscapeAttributeEntities(attributes.getValue(index));
   writer.write(quote);
 }
Beispiel #29
0
  /**
   * Returns attribute's value from the <code>attributes</code> container based on the <code>name
   * </code>.
   *
   * @param name
   * @param attributes
   * @return String value of the attribute if such attribute exists and null otherwise.
   */
  private String getAttributeValue(final String name, final Attributes attributes) {
    for (int i = 0; i < attributes.getLength(); i++) {
      if (attributes.getQName(i).toLowerCase().equals(name.toLowerCase())) {
        return attributes.getValue(i);
      }
    }

    return null;
  }
Beispiel #30
0
 public static Map<String, String> cleanseAttributes(Attributes in) {
   Builder<String, String> attrs = ImmutableMap.<String, String>builder();
   for (int i = 0; i < in.getLength(); i++) {
     String name = in.getQName(i);
     if (name.indexOf(':') != -1) name = name.substring(name.indexOf(':') + 1);
     attrs.put(name, in.getValue(i));
   }
   return attrs.build();
 }